Prettier

Sometimes you stumble upon a small tool or library that you fall in love with that you use and reuse for all of your projects. One of them is Prettier, I love how it takes away one pain-point from developing: keeping your code as readable as possible and enables team to actually get away from the subjective views on how code should be formatted. Decide on a formula that makes sense to you and your team and stick to it.

Why use Prettier?

No one, and I emphasize: no one, thinks a "tabs vs spaces"-discussions is a good way to spend your days in a team of developers. By using opinionated tools such as Prettier and adding them to your stack and make them automagically take care of stuff such as code format and indentation etc, you eliminate discussions, makes the code easier to read and hopefully also grabs some style errors and possible bugs that could come from wrongly formatted code.

How I use Prettier

I add prettier to all my front-end projects. The basic steps are:

  • Install Prettier as a dev dependency using NPM or Yarn
  • Create a .prettierrc file (I have one I more or less reuse for all my projects)
  • Create npm scripts that checks and rewrites according to your .prettierrc-file
  • Set up commit hook for running Prettier before your files are committed
  • Add the prettier check to your CI-configuration so your builds fail if files are not formatted according to your .prettierrc.

Install Prettier

npm install prettier --save-dev

My Basic .prettierrc

{
  "singleQuote": true,
  "printWidth": 80,
  "useTabs": false,
  "tabWidth": 2,
  "jsxBracketSameLine": true,
  "semi": true,
  "bracketSpacing": false
}

Gist here

NPM scripts for running Prettier

{
    "scripts": {
      "prettier-write": "prettier --write src/**/*.{js,ts,jsx,tsx,md,scss,css,json}",
      "prettier-check": "prettier --check src/**/*.{js,ts,jsx,tsx,md,scss,css,json}"
    } 
}

Prettier Commit Hooks with Husky and lint-staged

I use Prettier together with Husky and lint-staged to get a pre-commit hook that formats all the files I have configured to be "prettified" before they are commited (if they do not match the .prettierrc). This makes life a bit easier since you can write and do stuff the way you are used to and husky, lint-staged and prettier makes sure your output is formatted in a correct way.

I order to get this setup running, first, make sure you have Prettier as dev dependency and then run:

npx mrm lint-staged

That should put you in a good start for making sure your code looks better and take away some time spent on formatting stuff.

Back