paazmaya.fi

The Website of Juga Paazmaya | Stories about Web Development, Japanese Martial Arts, Hardware prototyping and travelling

JavaScript code quality validation with ESLint

ESLint is a JavaScript validation/linting tool running via Node.js and was created by Nicholas Zakas just about a year ago, in order to overcome some of the shortcomings of other similar tools such as JSHint and jslint. It even covers many of the code style validations done by JSCS.

The main difference in ESLint with the other mentioned tools is that the rules used for validation are build as modules and each of them can be configured differently. ESLint also has three different validation levels, not checked (0), warning (1) and error (2). The amount of rules available has increased throughout every release made, and in the latest version 0.6.1, there are already 119 validation rules. Custom rules can be added via configuration and they are all written in JavaScript, running through Node.js.

Similarly to JSHint, it can be configured with JSON formatted file, residing in the given folder in which the tool is run. The configuration format looks something similar to:

{
  "rules": {
    "block-scoped-var": 0,
    "brace-style": ["2", "stroustrup"],
    "consistent-this": [2, "self"],
    "no-unused-expressions": 1,
    "no-unused-vars": [2, "local"],
    "no-use-before-define": [2, "nofunc"],
    "no-warning-comments": 2,
    "quotes": [2, "single"],
    "radix": 2,
    "semi": 2,
    "sort-vars": 0,
    "space-after-keywords": [2, "always"],
    "space-in-brackets": 2,
    "strict": 2,
    "use-isnan": 2,
    "valid-jsdoc": [1, {
      "requireReturn": false
    }],
    "valid-typeof": 2,
    "wrap-iife": 0,
    "wrap-regex": 0
  },
  "env": {
    "browser": true,
    "node": true
  },
  "globals": {
    "jQuery": false,
    "Juga": true,
    "CodeMirror": false
  }
}

ESLint can be run directly from command line, by pointing to the possible configuration file and to the target files, for example:

eslint -c eslint.json Chatanyara.js

Additionally there are several plugins for different task runners, such as Grunt or Gulp, which can help shortening the commands and allowing to make more complex target configurations. A list of some of those plugins is available at the Integrations page. Even a Git precommit hook is listed there.