Prettier - Opinionated Code Formatter

What is prettier?

Prettier is an opinionated code formatter. That’s all.

✅ Language support

  1. JavaScript, including ES2017
  2. JSX
  3. Flow
  4. TypeScript
  5. CSS, Less, and SCSS
  6. JSON
  7. GraphQL
  8. Markdown, including GFM
  9. YAML

👉🏻 Life without Prettier

Dev (A): Hey, can you review my code?, Here is the PR link.

Dev (B): Sure. Hmm 🤔, this doesn’t seem right. Hey, can you do following changes in your PR?

  • Add spaces in between brackets.
  • Code is lenghty. Let’s keep the line width as 140?
  • Also follow 2 tab/space indent.

Dev (A): Sounds right. I will make the changes. Regarding #3 in above, let’s keep 2 space. Not tabs?

Dev (B): Sure, why not. Dev’s are still fighting for tab vs space. Let’s stick to space indent (Inner voice, Shannaro 👿).

Dev (B): Yoo, got some time to review my PR.

Dev (A): After reviewing, I thought we decided to keep 2 space as indent.

Dev (B): Oh yeah, I forgot 😱.

Dev (A): Commenting in Dev (B) PR…

  1. Add bracket in Arrow Funtions Parentheses.
  2. Can we not keep Trailing Commas?
  3. Quotes should be single not double.

Dev (B): Changes done. PR got merged. uff 🤯.

Dev (A): Wish there is some magical wand which will format the code for us instead of us wasting time while writing 😭.

👉🏻 Life with Prettier

Dev (A): Adding prettier to the project.

Step 1: Add prettier to package.json file.

yarn add prettier --dev --exact

Step 2: Add the .prettierrc.js config.

module.exports = {
  trailingComma: "never",
  tabWidth: 2,
  singleQuote: true,
  printWidth: 140
};

Step 3: Add prettier to pre-commit git hook.

yarn add husky lint-staged --dev

Step 4: Add the precommit hook in package.json file

"scripts": {
  "pretty": "prettier --write \"src/**/*.js\"",
  "precommit": "lint-staged && npm test"
  },
  "lint-staged": {
    "*.js": [
      "npm run pretty",
      "git add"
    ]
  }

Dev (B): Committing the code.

ga .
gc -m "Added header style fixes"

Dev (B): Ohhh, wow this is awesome. No more manual formatting and No need to discuss style in code review anymore 😋.

Dev (A): Yep, it took me just 10 mins. Also prettier is supported in most of the IDE’s.

Dev (A): I have it in my vscode and it formats file on save.

🎁 Popular open sources using prettier

  • Facebook
  • Webpack
  • React
  • Babel
  • Yarn

And many more.

📝 References:

I personally used and using the prettier in most of my projects/pet projects.

Thanks for reading my post. If you like it. Share it 😬.

Gokulakrishnan Kalaikovan

Gokulakrishnan Kalaikovan

Web Developer &Google Developer Expertbased in India, Bangalore.