Skip to content
Nate Radebaugh
Nate Radebaugh
Home
GitHub
Twitter
LinkedIn
Resume

Intro to Prettier code formatter

April 5, 2020 9:45 PM

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:

txt
1function HelloWorld({greeting = "hello", greeted = 'World'}) {
2if(!greeting){return null};
3
4return greeting+" "+greeted;
5}

and format it beautifully like

js
1function HelloWorld({ greeting = "hello", greeted = "World" }) {
2 if (!greeting) {
3 return null;
4 }
5
6 return greeting + " " + greeted;
7}

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

  1. Add prettier to your project

    shell
    npm install prettier --save-dev --save-exact
  2. Run against all your files

    shell
    npx prettier --write src/**/*
  3. Run prettier automatically when committing files

    shell
    npm install --save-dev pretty-quick husky

    Then add this config to package.json:

    package.json
    1{
    2 "husky": {
    3 "hooks": {
    4 "pre-commit": "pretty-quick --staged"
    5 }
    6 }
    7}

Further reading...