概要
以前はJSLint, JSHintなどが使われていましたが、最近はplugableなESLintがコードの検証に使われる様になってきました。
今回はその設定方法を簡単に説明します。
環境
- Node.js 6.6.0
- ESLint 3.5.0
インストールと設定
npmでインストールします。
$ npm install -g eslint
初回設定をします。
$ eslint --init ? How would you like to configure ESLint? (Use arrow keys) ❯ Answer questions about your style Use a popular style guide Inspect your JavaScript file(s)
矢印キーを使ってどの形式で設定を作成するかを決めます。今回は対話式にできる一番上のものを使います。そのままEnterします。
あとは質問に応じて進めていきます。
? Are you using ECMAScript 6 features? Yes ? Are you using ES6 modules? Yes ? Where will your code run? Node ? Do you use JSX? No ? What style of indentation do you use? Spaces ? What quotes do you use for strings? Single ? What line endings do you use? Unix ? Do you require semicolons? Yes ? What format do you want your config file to be in? JSON Successfully created .eslintrc.json file
生成された.eslintrc.json
は以下です。
{ "env": { "es6": true, "node": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } }
追加設定
上記の設定の他、個人的に設定したい以下の項目を入れていきます。
- インデントは半角スペース4つでなく2つに。
- switch文のcaseはネストさせる。
- console.logはerrorでなくwarningとして出す。
その他自分でカスタムしたい場合は List of available rules - ESLint - Pluggable JavaScript linter を見ながら設定すると良いです。
{ "env": { "es6": true, "node": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "error", 2, { "SwitchCase": 1 } ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "no-console": [ "warn", { "allow": ["warn", "error"] } ] } }
動作検証
試しにexpress-generatorで生成したコードに対して実行してみます。
$ eslint . /Users/jun06t/prog/sample/eslint/app.js 3:5 error 'favicon' is defined but never used no-unused-vars 40:35 error 'next' is defined but never used no-unused-vars 51:33 error 'next' is defined but never used no-unused-vars /Users/jun06t/prog/sample/eslint/routes/index.js 5:36 error 'next' is defined but never used no-unused-vars /Users/jun06t/prog/sample/eslint/routes/users.js 5:36 error 'next' is defined but never used no-unused-vars ✖ 5 problems (5 errors, 0 warnings)
よろしくないとされる部分が指摘されますね。
「これは許容したいな・・・」という場合は先ほどのルール表からno-unused-vars
といったエラーの文字列を検索すると設定方法が書かれています。