概要
create-react-app用のESLintをVSCodeでやる。
前提知識
ESLint自体はcreate-react-appすると自動的にインストールされている。
で、create-react-appした時のpackage.json
に↓があるのがポイント。
※react-app
というルール定義が存在していてそれを継承している形になっている
{
//...略...
"eslintConfig": {
"extends": "react-app"
},
//...略...
}
npm run start
すると、サーバが起動し、その中のメッセージで自動的にlintして警告を出したりしてくれるが、これはreact-app
というルールを使用していることになる。
設定
で、VSCodeにreact-app
のlintを同じように使用するためには、
1. VSCodeの拡張にESLintを入れる
2. ESLintのファイルを生成する
ctrl + shift + P
で、ESLint: create ESLint congiguration
を選択する。
ESLintの設定ファイル生成のコマンドラインが起動するので、↓を参考に設定。
ワークスペースのルートに、eslintrc.js
ファイルが生成される。
3. eslintrc.jsのベースルールをreact-appへ変更する
eslintrc.jsのextends
を、
'extends': 'eslint:recommended',
↓へ変更する。
'extends': 'react-app',
4. ファイル保存時に自動的にlintルールで整形されるようにする
ctrl + shift + P
で、ユーザー設定を開く
を選択する。
ユーザ
をワークスペース
へ変更する。
設定の検索
に、ESLint
と入力する。
Files: Auto Fix On Save
にチェックを入れる。
↓諸々含めた設定例。
{
"files.eol": "\n",
"editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true // importの自動編成
}
}
おまけ
- セミコロン付与
- インデントスペース4つ
- シングルクオート
- 末尾の空白を削除
- 複数空行禁止
のサンプルeslintrc.js
module.exports = {
'env': {
'browser': true,
'es6': true
},
'extends': 'react-app',
'globals': {
'Atomics': 'readonly',
'SharedArrayBuffer': 'readonly'
},
'parserOptions': {
'ecmaFeatures': {
'jsx': true
},
'ecmaVersion': 2018,
'sourceType': 'module'
},
'plugins': [
'react'
],
'rules': {
'linebreak-style': ['error', 'unix'],
'indent': [
'error',
4,
{ "SwitchCase": 1 }
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
],
"no-extra-semi": "error",
'no-trailing-spaces': [
"error",
{ "skipBlankLines": false }
],
'no-multiple-empty-lines': [
'error'
],
"no-unexpected-multiline": "error",
}
};