Adding Prettier to a Project

Add Prettier with a pre-commit hook and dedicate one commit to a full reformat

Woman's hand holding a brush up to an eyemakeup palette in the shape of a laptop
Take time to make your code prettier. Photo by Laura Chouette on Unsplash

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:

  1. A consistent linter/formatter for all projects in a particular language
  2. An autoformatter so developers didn't spend time "fixing" linter errors
  3. 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.

  1. Install prettier:
$ npm install --save-dev --save-exact prettier
  1. Create an empty config file to let tools know you're using Prettier:
$ echo {}> .prettierrc.json
  1. Create a .prettierignore file to let tools know which files NOT to format. node_modules are ignored by default. Some suggestions:
  1. Manually run Prettier to re-format all the files in the project:
$ npx prettier --write .
  1. Set up your code editor to auto-format on save for ease of use. See instructions for various editors.
  2. Set up commit hooks with pretty-quick and husky. First, install them as dev dependencies:
$ npm i --save-dev pretty-quick husky
  1. 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!

You might also like


If you liked this article and think others should read it, please share it.

These are webmentions via the IndieWeb and Mention this post from your site:

← Home