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.

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

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.

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!

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *