Validating JavaScript with Grunt and JSHint

Monday, August 25, 2014
by Sean McAlinden

JSHint is a great way to ensure your JavaScript is valid.

There is a JSHint plugin for Grunt which is really easy to use.

Following on from my Using grunt to minify javascript tutorial, I'm going to add JSHint to the project and validate my JavaScript.


Navigate to the root of the project and type the following at the command line:

npm install grunt-contrib-jshint --save-dev

This will add the following to your packages.json devDependencies section:

"grunt-contrib-jshint": "~0.10.0"



Add the following JSHint config to the initConfig method in the Gruntfile.js file.

jshint: {
    files: ['Gruntfile.js', 'Scripts/myTestJsFile.js'],
    options: {
        // options here to override JSHint defaults
        globals: {
            jQuery: true,
            console: true,
            module: true,
            document: true

Whilst you can see I have specified a single script, you can use wildcards to point at folders for example: Scripts/*.js.

Load Plugin

Load the plugin using the following:



Register Task

I don't want to run JSHint all the time so I am going to register the task with a different custom key, I am going to call this "˜validate':

grunt.registerTask('validate', ['jshint']);

Run JSHint

To run JSHint, at the root of your project simply type the following and hit enter:

grunt validate

If there are errors in the specified JS file they will show up in the command line along with the line numbers, really useful stuff.