What is “Lint”?
Running JSHint Manually
The easiest way to run JSHint is to go to the website, paste in your code, and hit the “Lint” button. That’s fine for one-off scripts, but not really suitable for professional web development.
Another option is to use the Node package manager to install a copy of JSHint. (You’ll need to install Node first, if you haven’t already.) If you use the -g option when you install JSHint, it will put a convenient command-line interface on your path.
Once JSHint is installed, you can “require” it in your build script. JSHint and JSLint both provide the same interface, and it’s not a particularly friendly one. There’s only one function exposed by the module: JSHINT. It takes the source code to check, a set of options, and an optional set of globals, and returns true or false depending on whether the lint succeeded or failed. It also populates an “errors” array on the JSHINT function with specific error messages.
The first parameter is the source code. You’ll need to load your files from the file system. To load a file, use the
readFileSync() function in Node’s
readFileSync() reads an entire file into memory. It takes a file encoding; if you’re not sure what to use, UTF-8 is usually a safe bet. Once you have the file, you can pass it to JSHint.
Your automated build will likely have a list of files to check, so you’ll need a function that calls Lint for each file and collates the overall “pass / fail” status as it goes.
The second parameter is an object containing your JSHint options. These options control what Lint complains about and what it allows to pass. They’re described in detail on the JSHint web site, so I won’t repeat that here.
The third parameter is optional. It’s an object containing your global variables. If you set the “undef” option to “true”, then JSLint will complain if you use any variables that haven’t been explicitly declared. This third parameter allows you to make exceptions to the rule. For each global variable name you include, you set it to “true” if your code is allowed to change the variable, or “false” if it isn’t.
Interpreting JSHint’s Results
When you run JSHint, it returns true or false according to whether or not your code passed. That’s enough to cause your build to fail when you need it to, but you’ll also want to print out the details of what Lint found.
To do that, you’ll want to examine JSHint’s
errors array. Some elements of the array are blank--you can just skip those. The rest are objects with three properties:
line, which is the line number;
evidence, which is the source code containing the problem; and
reason, which is Lint’s error message. Sometimes
evidence are left out, so you’ll want to check for that.
Thanks for watching, and I’ll see you next time!