Skip to content

Intro to Prettier code formatter

April 5, 2020


Use prettier to focus on the code and not on the formatting.


Prettier is a great tool for automatically formatting your code in a consistent way across your codebases, regardless of individual contributor preferences.

Prettier can take something like:

function HelloWorld({greeting = "hello", greeted = 'World'}) {
if(!greeting){return null};

return greeting+" "+greeted;
}

and format it beautifully like

function HelloWorld({ greeting = "hello", greeted = "World" }) {
  if (!greeting) {
    return null;
  }

  return greeting + " " + greeted;
}

What is Prettier?

  • An opinionated code formatter
  • Supports many languages
  • Integrates with most editors
  • Has few options

Why?

  • You save and code is formatted
  • No need to discuss style in code review
  • Saves you time and energy
  • And more:
    • Helping Newcomers
    • Writing code
    • Easy to adopt
    • Clean up an existing codebase

Supported Languages

  • JavaScript
    • JSX
    • TypeScript
    • JSON
  • CSS
    • SCSS
  • HTML
    • Vue
    • Angular
  • Markdown
  • YAML

Text Editor Support

  • VSCode
  • Atom
  • Sublime

Get Started

  • Add prettier to your project

    npm install prettier --save-dev --save-exact
    
  • Run against all your files

    npx prettier --write src/**/*
    
  • Run prettier automatically when committing files

    npm install --save-dev pretty-quick husky
    

    Then add this config to package.json:

    package.json
    {
      "husky": {
        "hooks": {
          "pre-commit": "pretty-quick --staged"
        }
      }
    }
    

Further reading...