Add Prettier to your project

Reformat your project with prettier and husky pre-commit, to ensure beautifully formatted code.

prettier.png

When you work with multiple people in a team it's commonly known that the format of your code is incossistend. By adding a formatter to your project(s) you could keep it neat and tidy. In this article I will show you how you could add Pretter and a pre-commit hook to your project.

  1. Install Prettier
yarn add -D prettier
// or
npm install --save-dev prettier
  1. Create a .prettierrc file with the follwing contents.
{
  "singleQuote": true,
  "bracketSpacing": true,
  "printWidth": 120
}
  1. Some files need to ignored by our formatter. So go ahead and create a file name .prettierignore in the root of you project. Add the files or folders you would like to ignore, for example:
./dist
  1. In our package.json add the "format": "npx prettier --write ." in your script section.
...
"version": "0.0.0",
"scripts": {
    "start": "node index.js",
    "format": "npx prettier --write ."
 },
...

When we this script, it wlll reformat the files in your project. Optionally we can automate this process by installing husky and pretty-quick.

  1. Install husky and pretty-quick
yarn add -D husky pretty-quick
// or
npm install --save-dev husky pretty-quick
  1. Finally add the following to your package.json
"husky": {
  "hooks": {
    "pre-commit": "pretty-quick --staged"
  }
},

Now when you commit your work, your code will automatically be formatted. Thanks for reading!

@ Copyright Vonlof (Edept B.V.) info@vonlof.com