Related Articles

Back to Latest Articles

How to format JavaScript automatically with Prettier and Git

How to integrate Prettier and Git to have your JavaScript automatically formatted before every commit.

Tilo Mitra
How to format JavaScript automatically with...

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!



Show Comments (0)


Related Articles


13 best practices to secure your NodeJS web application

Everyone agrees that web application security is very important but few take it seriously. Here's a 13-step security checklist that you should follow before deploying your next...

Posted on by Tilo Mitra
Vanilla Javascript

How do JavaScript Page Lifecycle Events work?

Let's talk about the different JavaScript events that fire when loading and unloading a page.

Posted on by Tilo Mitra


Get future articles sent directly to your inbox.

I only send emails when I write something new.