Monday, January 4, 2016

JSHint + AngularJS = Tight as a drum

So, in the development of the new version of ParkInfo Mobile, I wanted to run things through some code-quality checks as a matter of course. I'm good at what I do, but having a second pair of eyes (cybereyes!) look for missing semicolons etc. sure won't hurt.

I went with JSHint and I really like the results.
  • JSHint noticed a few stragglers such as semicolons, trivial stuff that could lead to larger goofs. Making use of JavaScript statement-chains crossing lines, means that a stray semicolon or a missing semicolon cause truly bizarre malfunctions. For this reason I prefer not to use the multi-line syntax, but with Angular it does happen a lot so this extra check is nice.
  • JSHint also complains about undeclared variables, e.g. L which is declared in leaflet.js and angular which is declared in angular.js These weren't errors at all but are easily permanently silenced... and could have been invaluable if the "undeclared global" were actually a typo.
  • JSHint also reports unused variables. In most cases this was a callback that receives an error object, and we don't use the error object. But in a few cases it was dependency injections which were no longer in use. So a second use of JSHint was to check for unused dependencies and for erroneous undeclared dependencies. Very nice.
So, I threw together a quick-n-dirty shell scrip to run everything through JSHint, and I run it when I get ready to push.

Step 1, install JSHint via npm. You're used to this if you use Cordova:

npm install -g jshint
Step 2, set up this script. Heck, add it to your source archive:
#!/bin/sh

for js in www/index.js www/controllers/*.js ; do
    echo "********** CHECKING $js"
    echo ""

    jshint $js

    echo ""
done
It's dead simple, nothing special... but it does keep things a bit tighter, and makes for easy and automated checks for some common goofs.

Now, the other tool commonly used here is JSLint. But so far I'm not impressed with it. Reporting unused variables and potential typographical errors is great, but JSLint reports truly stupid stuff such as having a space after the colon in an object literal, stuff which truly has no impact nor potential for impact. Maybe later, but not today.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.