INFRA

eslint

ESLint

参考:ESLint 最初の一歩

ESLint は JavaScript のための静的検証ツールです。コードを実行する前に明らかなバグを見つけたり、括弧やスペースの使い方などのスタイルを統一したりするのに役立ちます。同様のツールとしては JSLint, JSHint 等があります。

インストール

$ npm i -D eslint

package.jsonの設定

グローバルインストールでないので、npmから実行できるようにします。 package.jsonのscriptsを下記のようにします。

"scripts": {
"lint": "eslint src",
"lint-init": "eslint --init"
},

初期化(設定ファイルの作成)

eslint —initで対話的に設定ファイルが作成できます。グローバルインストールでないので、eslint —initというコマンドがそのままは使えない為、上記で設定したnpmのscriptsを使います。設定ファイルの作成が終わったら、上記のlint-initは不要です。

$ npm run lint-init

色々聞かれたので、popularのAirBnBのjsonにとりあえずしてみました。設定ファイル、.eslintrc.jsonが出力されます。 .eslintrc.jsonの中身

{
"extends": "airbnb",
"plugins": [
"react",
"jsx-a11y",
"import"
]
}

jsファイルを適当に作ってみる

hoge.js

function hoge(name){
var msg = 'you are' + name;
return msg
}
alert(hoge('Abe'));

使ってみる

$ npm run lint hoge.js

使えました。下記が表示されました。

1:20 error Missing space before opening brace space-before-blocks
1:21 error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
2:5 error Expected indentation of 2 spaces but found 4 indent
2:5 error Unexpected var, use let or const instead no-var
2:15 error Unexpected string concatenation prefer-template
2:32 error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
3:5 error Expected indentation of 2 spaces but found 4 indent
3:15 error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
3:15 error Missing semicolon semi
4:2 error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
5:1 error 'alert' is not defined no-undef
5:1 warning Unexpected alert no-alert
5:20 error Newline required at end of file but not found eol-last

おー厳しい。

どんなルール設定にしたら最適なのでしょうか? とりあえずAirbnbに合わせることはいいことだとは思いますが。あと、改行文字とか、ブロックの前にスペース空けるとかは、自動整形とかあると便利なのですが、あるのでしょうか?

結構Airbnbは人気みたい。 visual studio codeでは、Shift+Alt+Fで自動整形できる。拡張機能にeslintもあるし、eslintの設定は、eslintrc.jsonを読んでくれる。eslintはデフォルトで、node_modulesの中はみないとどこかに書いてあったんだけど、visual studio codeのeslint拡張は見ちゃうみたい。.eslintignoreで設定したら消えた。改行文字もvisual studio codeの設定変更した。これでエラー消えた。