ESLint触った
VSCodeにESLintの拡張機能入れて触ったのでメモ
Node.js 8.10.0eslint 5.16.0dbaeumer.vscode-eslint 1.9.0
npm install eslint --save-dev
パッケージ直下に .eslintrc.json
ファイルを作って、そこに文法チェックのルールを書いて使う。
{
"extends": [
"eslint:recommended"
],
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2017
},
"rules": {
"no-console": "off",
"indent": ["error", "tab", {"SwitchCase": 1}],
"semi": ["error", "always"]
}
}
eslint:recommended
... ルールを自分で書かなくても、いい感じにチェックしてくれるようになる。env.node = true
... Node.js用にチェックする。(備考: ブラウザ向けならenv.browser
)env.es6 = true
... ES6 (2015) 用にチェックする。これを指定しないと、Promise
が定義されてない ('Promise' is not defined.) 扱いされてしまった。parserOptions.ecmaVersion = 2017
...async/await
を使いたかったので。rules.no-console = off
... これを指定しないと、console
が定義されてない ('console' is not defined.) 扱いされてしまった。rules.indent = ["error", "tab", {"SwitchCase": 1}]
... インデントはタブ、switch
内もひとつ下げる (デフォルトだと、むしろ下げたらエラーらしい)。rules.semi = ["error", "always"]
... 文末のセミコロン強制!!
細かいことは公式のドキュメントを読もう
List of available rules - ESLint - Pluggable JavaScript linter
ところでJavaScriptのインデントって、スペース2個が主流らしいんだけど、個人的には狭くて読みにくくて嫌。
なんでだろう?? スペース2個なら rules.indent
は ["error", 2, {"SwitchCase": 1}]
になる。しばらくこれでやってみれば解るのかな……。
eslint --init
eslint --init
すると、質問に答えていい感じの設定を作ってくれる!
? How would you like to use ESLint? (Use arrow keys)
To check syntax only
> To check syntax and find problems
To check syntax, find problems, and enforce code style
? What type of modules does your project use? (Use arrow keys)
JavaScript modules (import/export)
> CommonJS (require/exports)
None of these
? Which framework does your project use?
React
Vue.js
> None of these
? Where does your code run?
( ) Browser
>(*) Node
? What format do you want your config file to be in? (Use arrow keys)
JavaScript
YAML
> JSON
Local ESLint installation not found.
The config that you've selected requires the following dependencies:
eslint@latest
? Would you like to install them now with npm? (Y/n) n
これで作られた .eslintrc.json
がこう↓
{
"env": {
"commonjs": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
}
}
VSCodeでESLintが動かない時は
以下記事にまとめました