Linting JavaScript in GNU Emacs
Setting eslint and jscs for GNU Emacs
With any programming language, when you do some client or day job work, you need to deliver quality software. When you contribute to FLOSS projects, you have to follow some style guides specified for that project. Great help with all of that are linters and style checkers.
JavaScript world if full of those… Just try to search npm package with word 'lint'…
My choice
However, flycheck
package for GNU Emacs supports some of the biggest names: gjslint
, jshint
, eslint
as linters and jscs
and standard
/semistandard
as style checkers. I use only eslint (best ES6 support) and jscs (great support for JSDoc).
Both can be installed using npm
. I also install babel-eslint
because almost all my projects use babel
.
Both tools require configuration files in project directory in order to work correctly.
ESLint
Install with npm:
$ npm install -g eslint babel-eslint
You can install modules without -g
flag, but then you need to set $PATH in Emacs.
Create .eslintrc
file in your project directory (or your $HOME directory) with following:
{
"extends": "eslint:recommended",
"parser": "babel-eslint",
"rules": {
"strict": 0
}
}
JSCS
Again, install with npm:
$ npm install -g jscs
In order to create .jscsrc
file, best way is to point to your existing JavaScript file and then jscs
will offer you some presets based on your coding style.
$ jscs --auto-configure <directory with your files or single js file>
In my example case I got config under this paragraph using js file with 20 lines… Not really correct style for mine taste, so please use a good example JavaScript file when you do this.
{
"preset": "airbnb",
"requireSpacesInAnonymousFunctionExpression": null
}
You can take it from there and tweak it if needed.
I also like to check JSDoc documentation in JavaScript files. In order to do that add following to your .jscsrc
file:
{
"preset": "airbnb",
"requireSpacesInAnonymousFunctionExpression": null,
"maxErrors": -1,
"esnext": true,
"plugins": [
"jscs-jsdoc"
],
"jsDoc": {
"checkAnnotations": "jsdoc3",
"checkParamExistence": true,
"checkParamNames": true,
"checkRedundantParams": true,
"checkReturnTypes": true,
"checkRedundantReturns": true,
"requireReturnTypes": true,
"checkTypes": "strictNativeCase",
"enforceExistence": true,
"requireHyphenBeforeDescription": true,
"requireParamDescription": true,
"requireReturnDescription": true
}
}
That 'maxErrors' is in order to ask for all errors, without limit.
GNU Emacs settings
Well, flycheck
will use eslint
and then stop with collecting errors and warnings. jscs
is never called if eslint
is present. In most modes flycheck
will chain checkers, one after another, but not for JavaScript. In order to chain checkers, add following somewhere in init.el
:
(with-eval-after-load 'flycheck
;; Run javascript-jscs to run after javascript-eslint.
(flycheck-add-next-checker 'javascript-eslint '(t . javascript-jscs)))