Using JSHint to Check for Errors and Problems

We’ve written quite a bit of JavaScript code in this chapter; some of it might not work right, and some of it might not conform to coding standards that other Grunt plug-ins want. We can use JSHint to detect errors and problems so we can fix them.[16] And best of all, we can do it easily with Grunt.

First, we install the grunt-contrib-jshint plug-in:

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

Next, we create a file called .jshintrc, which contains the rules we want to test our code against. We’ll use the rules that other Grunt plug-ins use. Place the following lines of code in the file—you don’t have to type in the comments for this to work, but you may want them anyway so you don’t forget what these options do:

grunt-open-with-chrome/.jshintrc
 
{
 
"node": true, ​// For NodeJS
 
"undef": true, ​// Require all non-global variables to be declared
 
"curly": true, ​// Require curly braces for blocks and scope
 
"eqeqeq": true, ​// Require "===" instead of "==" for equality
 
"immed": true, ​// Must wrap immediate invoked functions in parens
 
"latedef": true, ​// Must define functions and variables before use
 
"newcap": true, ​// Constructor functions must be capitalized
 
"noarg": true, ​// Don't allow 'arguments.caller' and 'arguments.callee'
 
"sub": true, ​// Allow '[]' even if dot notation could be used
 
"boss": true, ​// Allow assignments where comparisons might be expected
 
"eqnull": true ​// Allow use of '== null'
 
}

Then we set up the Grunt task for JSHint by including the NodeJS module and configuring its options:

grunt-open-with-chrome/Gruntfile.js
 
grunt.loadNpmTasks(​'grunt-contrib-jshint'​);
 
grunt.config(​"jshint"​, {
 
all: [
 
'Gruntfile.js'​,
 
'tasks/**/*.js'
 
],
 
options: {
 
jshintrc: ​'.jshintrc'​,
 
},
 
});

We’re configuring this task to look at all of the JavaScript files within the task folder, no matter how many folders deep they are. This ensures we check the lib folder too. We also let it look at the Gruntfile itself.

And now we can run the following to check for errors.

 
$ ​grunt jshint
 
Running "jshint:all" (jshint) task
 
>>​ 3 files lint free.
 
 
Done, without errors.

Any errors or warnings found will stop Grunt from processing any other tasks, so this is a great tool to add into a final build process to ensure that you’ve fixed all of your code issues before deploying things to production.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.116.159