Interested in working with us? We are hiring!

See open positions

How to add JSCS to your pre-commit hook

Timothée Boucher Written by Timothée Boucher, March 05, 2014

I recently came across JSCS and thought it would be a great addition to our git flow to enforce consistent code style for all of our JavaScript code.

JSCS is a code style checker for JavaScript. It lets you decide if you prefer your if’s with or without a space after them; if you’re OK with declaring multiple variables with one var keyword; if your lines shouldn’t go over 80 characters; etc. A lot of it is a matter of taste of course, but the main goal is consistency.

So far we’ve been pretty good at having a fairly homogeneous style in our JavaScript files, but as our team grows, new people need to adapt to the implied preferences of our code base. Adding JSCS means that our style guide is codified in JSCS’ config file and less prone to interpretation.

Having it as part of our pre-commit hook results in less time spent in code reviews saying things like “if you don’t mind, you missed a space here”. Some might think it’s nitpicky, but we’re looking at it with the broken windows theory in mind.


So, here is the addition we made to our precommit hook to run JSCS on any JavaScript files that are staged:

It’s fairly simple: we use git checkout-index to output the staged files to a temporary folder, run JSCS against it and print out any errors, and stop the commit if there are any errors.

The main drawback is that you can only really run JSCS against a full file and not just the diff. So even if you change only one line in a file, you’ll have to fix all the existing errors in that file, and the related pull request will be more cluttered than necessary. But that should only be a transitional period: once all your files have been cleaned up, you will get errors only on the changes you’ve made.

Here are some tips to keep the initial cleanup manageable:

How to add this to your pre-commit hook

  1. Install JSCS (see instructions).
  2. Create a file named .jscs.json with your preferred options. As a starting point, you can check our current configuration.
  3. Paste the script above to your pre-commit hook in .git/pre-commit. (see the git documentation for more details) You’ll need to add JSCS_PATH to your environment, pointing to where jscs lives.
  4. Proceed to commit perfectly styled code!