Monthly Archives: July 2012

Validating a project’s JavaScript code using Grunt and JSHint

If you haven’t used it before, Grunt is a task-based command line build tool for JavaScript projects, similar to Ant.

Grunt is built on top of Node.js and can be installed using npm (see Installing grunt and Introducing Grunt for more details).

Once installed, linting a JavaScript project is very easy. Simply create a grunt.js file in your project’s root directory and paste the following code:

#!/usr/bin/env node

module.exports = function (grunt) {
    "use strict";

    // Project configuration.
    grunt.initConfig({
        lint: {
            all: ["grunt.js", "**/*.js"]
        },
        jshint: {
            options: {
                browser: true,
                curly: true,
                eqeqeq: true,
                newcap: true,
                undef: true,
                eqnull: true,
                node: true
            },
            globals: {
                exports: true,
                Ext: false,
                console: false,
                alert: false,
                prompt: false
            }
        }
    });

    // Default task.
    grunt.registerTask('default', 'lint');
};

Then, simply open a Terminal window in your application’s root folder (where you saved the grunt.js file earlier), type `grunt` and each of your *.js files will be linted using the specified JSHint options:

$ grunt
path.existsSync is now called `fs.existsSync`.
Running "lint:all" (lint) task
Lint free.

Done, without errors.