Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Configuring jshint as a pre-commit hook for your nodejs applications

Although you can always run a jshint task any­time by your­self, its still a good idea to be able to auto­mat­i­cally run a jshint just before mak­ing a com­mit to ensure that you are not acci­den­tally check­ing in code that has a silly mistake.

NOTE: The project source code for this post can be accessed from our node starter kit project at github in this com­mit.

This is some­thing that is well suited to a pre-commit task. Edit­ing the .git/hooks/pre-commit is one way of doing this. But since hooks are not com­mit­ted as part of your repos­i­tory code, its not really as effec­tive if you want to ensure that even your col­lab­o­ra­tors are adhere­ing to the same standards.

A bet­ter strat­egy is to setup a grunt task that con­fig­ures a pre-commit githook for you.

npm install grunt-githooks --save-dev

Now, lets con­fig­ure our grunt task ‘githoooks’.

We will cre­ate a seper­ate file in our grunt folder to save the set­tings of our githooks task and export its set­ting as a mod­ule. Lets call that file githooks.js.


module.exports = {
  all: {
    'pre-commit': 'jshint',

Now, in our Gruntfile.js, add the fol­low­ing lines of code.

grunt.config( 'githooks', require('./grunt/githooks.js') );

Now your grunt task that sets up your pre-commit githook is ready. The only thing remain­ing is to run this grunt task so that it cre­ates a pre-commit file in your .git/hooks directory.

grunt githooks

From now on, any­time you try to com­mit, jshint will exe­cute before git even attempts to open the com­mit mes­sage window.

There is one big gotcha here. The grunt task setup this way exam­ines the files in the work­ing direc­tory instead of the index. This might not be an issue for you if you are the kind of per­son who always com­mits when your work­ing direc­tory = index, but in case you plan to com­mit only your staged changes, you prob­a­bly want to stash only the changed made in your work­ing direc­tory before run­ning the com­mit. The eas­i­est way to do that is by run­ning the command

git stash save --keep-index

Now you can go ahead and com­mit your changes and jshint will only run on the files that are ready for com­mit since your stage = work­ing direc­tory. Once you have com­mit­ted your chages, just pop your stash using the command

git stash pop

and you will get all your working-directory-only changes back.

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...