1

Adding Prettier to a Project

 2 years ago
source link: https://dev.to/thegreengreek/adding-prettier-to-a-project-13f6
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Adding Prettier to a Project

Adding Prettier to a Project

Jul 1 Originally published at sia.codes

・2 min read

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.

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
Enter fullscreen modeExit fullscreen mode

(2) Create an empty config file to let tools know you're using Prettier:

$ echo {}> .prettierrc.json
Enter fullscreen modeExit fullscreen mode

(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.*
Enter fullscreen modeExit fullscreen mode

(4) Manually run Prettier to re-format all the files in the project:

$ npx prettier --write .
Enter fullscreen modeExit fullscreen mode

(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
Enter fullscreen modeExit fullscreen mode

(7) Finally, add the pre-commit instructions to your package.json file:

"husky": {
  "hooks": {
    "pre-commit": "pretty-quick --staged"
  }
},
Enter fullscreen modeExit fullscreen mode

Now when you commit your changes, files in the commit will automatically be formatted!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK