Adding Prettier to a Project
Sia Karamalegos
Posted on July 1, 2021
While working at a smaller dev shop, our team hit the point at which the inconsistent code formats between and within projects was becoming a pain. Our needs included:
- A consistent linter/formatter for all projects in a particular language
- An autoformatter so developers didn't spend time "fixing" linter errors
- A tool readily available in tools like VS Code which could apply changes on save
We decided to go with Prettier. We also added a pre-commit hook to ensure that all code changes complied with the new authoritarianism.
I initially published this as a gist to help when setting up new projects at that company. Today, it was useful for a client I was working with, so I'm sharing it now in an article in case the same use case fits for you, and you'd like a handy reference.
The Steps
Most of these steps can be found in the docs and through other links in the docs.
A key step here is to run Prettier on all the files in a separate commit. You don't want to pollute all your future pull request diffs with formatting changes.
(1) Install prettier:
$ npm install --save-dev --save-exact prettier
(2) Create an empty config file to let tools know you're using Prettier:
$ echo {}> .prettierrc.json
(3) Create a .prettierignore
file to let tools know which files NOT to format. node_modules
are ignored by default. Some suggestions:
build
coverage
.package-lock.json
*.min.*
(4) Manually run Prettier to re-format all the files in the project:
$ npx prettier --write .
(5) Set up your code editor to auto-format on save for ease of use. See instructions for various editors.
(6) Set up commit hooks with pretty-quick and husky. First, install them as dev dependencies:
$ npm i --save-dev pretty-quick husky
(7) Finally, add the pre-commit instructions to your package.json
file:
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
},
Now when you commit your changes, files in the commit will automatically be formatted!
This article was originally published on sia.codes. Head over there if you like this post and want to read others like it, or sign up for my newsletter to be notified of new posts!
Posted on July 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.