JSHint is a linting tool which helps you detect potential problems with your code. Things like detecting global variables, missing semicolons, invalid use of the typeof operator and unused/undefined variables. Paired with a plugin to your favorite editor, you’ll get a nice second fair of eyes on your code. You can also hook it up to run as part of your test suite, to ensure you don’t commit code that does not follow your standards. JSHint is configurable using a .jshintrc file in the root of your project folder – and there are a whole range of options to tweak it to your preferred style.
JSCS is another great tool. This one usually won’t uncover errors in your code like JSHint, but rather with the style of your code. It’s very easy to set up, yet it has a large set of rules to tweak it to the exact style you want to follow. These rules can be defined in a .jscsrc file in the root of your project folder, in the same was as JSHint (it also lets you put them in your package.json file if you prefer that). At VG, we picked a preset which matched our style the most and tweaked the few options that were not quite as we wanted it.
With these two tools in place, you can have fully automated validation of your javascript with very little effort. If you want to automatically run JSHint and JSCS as part of the testing process, simply put them in your package.json
file as a pretest step:
1 2 3 4 5 6 7 | [code language="js"] "scripts": { "lint": "jshint .", "cs": "jscs .", "pretest": "npm run lint && npm run cs" } [/code] |
Just be sure to add node_modules to your ignores for the respective tools, so you don’t end up linting third-party code ☺
Note: I recently wrote a long blog post about how to write, test and publish javascript modules. It also covered some quality assurance, such as running JSHint as part of the testing process.