How to format JavaScript automatically with Prettier and Git



Prettier is a new code formatter for JavaScript developed at Facebook.  Unlike traditional formatters, it is opinionated and can work with no configuration. Prettier makes your JavaScript be easy-to-read and follow a specific convention. It also works with Flow, TypeScript, JSON, CSS, and more.

If you’ve used Prettier before, you may have gone with a version that is integrated into your editor of choice. I’m normally using VS Code, so I have Prettier run every time I save a file.

That’s great when I’m the only developer working on the project, but what if you have multiple developers? Sometimes, my personal Prettier options (4 spaces, double quotes for commas, etc.) are different from my colleague’s.

For these cases, we’ve made Prettier and Git work together. Prettier runs on a pre-commit git hook via the precommit script.

To do this, first install Prettier, lint-staged and husky as dev dependencies for the project.

npm install prettier lint-staged husky --save-dev

Next,  add the following to your application’s package.json.

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.js": [
      "./node_modules/prettier/bin/prettier.js --tab-width 4 --write",
      "git add"
    ]
  }
}

This says that whenever a git commit is triggered, Prettier will run with the provided options on all *.js files, and these files will then be added to the commit.

This is how it’ll look when you commit your code next time.

/code/web/my-app my-test-branch*
❯ git commit -m 'change date formatting'
husky > npm run -s precommit (node v8.4.0)

 ✔ Running tasks for *.js
[my-test-branch 57a53ea6] change date formatting
 1 file changed, 1 insertion(+), 1 deletion(-)

It’s important to note that no additional commits are created. Your existing commit is modified by running Prettier on any JS files that you committed. If you wanted to create a separate commit, you would use a postcommit hook.

Happy coding!