ESLint は JavaScript によるソースコードをチェックするツール。構文チェックなどして、バグになりやすいコードを調べることができる。

JavaScript 向けのソースコードチェッカーとしては、他に JSLintJSHint というものもあるけど、最近は、この ESLint が流行りみたいで、特徴は自由度が高いことらしい (pluggable になっているとか)。

今回の環境: Mac OS X Yosemite


$ uname -mrsv
Darwin 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64

Node.js はインストール済み。


$ node --version
v0.10.29

$ npm --version
1.4.14

ESlint をインストール。


$ npm install -g eslint

$ eslint --version
v0.20.0

適当なサンプルコード。


$ cat hello.js 

var message = 'hello, world.';

var a =  0;
var b = 1;

var c;

if(a < b){
  c = a + "<" + b;
}else{
  c= "hello, javascript";
}

d = message + ": " + c;

console.log(d);

サンプルコードを実行。ちゃんと動いている。


$ node hello.js 
hello, world.: 0<1

サンプルコードを eslint コマンドでチェックしてみたら、すごく怒られた( ´∀`)


$ eslint hello.js 

hello.js
   2:14  error  Strings must use doublequote      quotes
   4:9   error  Multiple spaces found before '0'  no-multi-spaces
  12:3   error  Infix operators must be spaced    space-infix-ops
  15:0   error  "d" is not defined                no-undef
  17:0   error  Unexpected console statement      no-console
  17:0   error  "console" is not defined          no-undef
  17:12  error  "d" is not defined                no-undef

✖ 7 problems (7 errors, 0 warnings)

「Strings must use doublequote」とあるのは、文字列を囲むのはシングルクォートじゃなくて、ダブルクォートにするようにとのこと。

「Multiple spaces found before '0'」は、空白文字が2文字以上あるよという警告。

「Infix operators must be spaced」は、演算子の前にはスペースを空けるようにと。

「"d" is not defined」は、 var が付いていないという警告。

警告に従って (警告っていうか ESLint 的には error らしいけど) hello.js を修正。


$ cat hello.js 

var message = "hello, world.";

var a = 0;
var b = 1;

var c;

if(a < b){
  c = a + "<" + b;
}else{
  c = "hello, javascript";
}

var d = message + ": " + c;

console.log(d);

もういちど、 eslint コマンドでチェック。


$ eslint hello.js 

hello.js
  17:0  error  Unexpected console statement  no-console
  17:0  error  "console" is not defined      no-undef

✖ 2 problems (2 errors, 0 warnings)

だいぶエラーが減った(*´ω`*)

残っているエラーは console.log のところ。

ESLint のデフォルト設定的には console.log は使っちゃダメなのか。。。

Node.js では console.log を普通に標準出力として使うと思うので、これを許可したい。

ESLint の公式ドキュメント Documentation - ESLint - Pluggable JavaScript linter を見ると、Node.js 環境向けの設定があった。

設定は、 ESLint の設定ファイル .eslintrc に書く (package.json にも書けるらしい)。


$ cat .eslintrc 
{
  "env": {
    "node": true,
  }
}

これで、eslint を実行してみたら、エラーが無くなって、何も出力されなくなった(*´∀`*)


$ eslint hello.js

細かい設定は Documentation - ESLint - Pluggable JavaScript linter に載っているので、いろいろカスタマイズはできそう。

tags: eslint javascript

Posted by NI-Lab. (@nilab)