Be the first user to complete this post

  • 0
Add to List

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

Although you can always run a jshint task anytime by yourself, its still a good idea to be able to automatically run a jshint just before making a commit to ensure that you are not accidentally checking 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 commit. This is something that is well suited to a pre-commit task. Editing the .git/hooks/pre-commit is one way of doing this. But since hooks are not committed as part of your repository code, its not really as effective if you want to ensure that even your collaborators are adhereing to the same standards. A better strategy is to setup a grunt task that configures a pre-commit githook for you.
npm install grunt-githooks --save-dev
Now, lets configure our grunt task 'githoooks'. We will create a seperate file in our grunt folder to save the settings of our githooks task and export its setting as a module. Lets call that file githooks.js. grunt/githooks.js
module.exports = {
  all: {
    'pre-commit': 'jshint',
  }
};
Now, in our Gruntfile.js, add the following lines of code.
grunt.config( 'githooks', require('./grunt/githooks.js') );
grunt.loadNpmTasks('grunt-githooks');
Now your grunt task that sets up your pre-commit githook is ready. The only thing remaining is to run this grunt task so that it creates a pre-commit file in your .git/hooks directory.
grunt githooks
From now on, anytime you try to commit, jshint will execute before git even attempts to open the commit message window. Gotchas There is one big gotcha here. The grunt task setup this way examines the files in the working directory instead of the index. This might not be an issue for you if you are the kind of person who always commits when your working directory = index, but in case you plan to commit only your staged changes, you probably want to stash only the changed made in your working directory before running the commit. The easiest way to do that is by running the command
git stash save --keep-index
Now you can go ahead and commit your changes and jshint will only run on the files that are ready for commit since your stage = working directory. Once you have committed your chages, just pop your stash using the command
git stash pop

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




Also Read:

  1. Send email using nodejs and express in 5 simple steps
  2. Find the environment variables of a nodejs process in linux
  3. Creating a simple event emitter using nodejs
  4. nodejs: generate uuid / guid