Format your JavaScript with prettier before committing

Have you tried jlongster’s prettier yet? It’s an opinionated command-line tool for automatically formatting your JavaScript. No more arguing about semicolons or line breaks or comma placement: prettier guarantees consistent styling by parsing your JavaScript to an AST and then pretty-printing the results. (Relatedly, gofmt is one of the things I loved about using Golang.)

Of course, having to manually run prettier is….work. I’d much rather have a git hook to magically take care of this for me. This way, you can be sure that any JavaScript changes you commit are properly formatted.

Adding a pre-commit hook to format your modified JavaScript files

Save the following as .pre-commit.sh in your repo:

git diff — name-only HEAD | grep ".*\.js" | xargs prettier — write

Now run the following commands:

$ chmod +x .pre-commit.sh
$ ln -s -f ../../pre.-commit.sh .git/hooks/pre-commit
$ git add .pre-commit.sh; git commit -m "Add pre-commmit.sh"

Ta-da. That’s all you need. prettier will now run against your modified JavaScript files whenever you commit code.

How does it work?

We created a shell script (named .pre-commit.sh ) and made it executable using chmod . Then we created a link to it at .git/hooks/pre-commit, which is where git looks to find a pre-commit hook. As the name suggests, pre-commit hooks are run before each commit. We then committed the script to our git repo. (I like keeping track of my git hooks in the same repo.)

The script itself does three things:

  • Use git diff name-only HEAD to find the file names for both staged and unstaged files which have changes
  • Filters those filenames for those which end in .js
  • Pipes those files as arguments to prettier, and uses the --write flag to instruct prettier to re-write those files

And…that’s it. Add this to your repo, and stop worrying about code style in your JavaScript.

And while you’re at it, go thank jlongster for writing such a nice tool.