LoginSignup
3
4

More than 3 years have passed since last update.

create-react-appで生成したReactのESLintをVSCodeでやる(自動整形付き)

Last updated at Posted at 2019-12-01

概要

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を入れる

そのまま。↓を入れる。
image.png

2. ESLintのファイルを生成する

ctrl + shift + P で、ESLint: create ESLint congiguration を選択する。
ESLintの設定ファイル生成のコマンドラインが起動するので、↓を参考に設定。
image.png

ワークスペースのルートに、eslintrc.jsファイルが生成される。

3. eslintrc.jsのベースルールをreact-appへ変更する

eslintrc.jsのextendsを、

'extends': 'eslint:recommended',

↓へ変更する。

'extends': 'react-app',

4. ファイル保存時に自動的にlintルールで整形されるようにする

ctrl + shift + P で、ユーザー設定を開く を選択する。
ユーザワークスペースへ変更する。
image.png
設定の検索に、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",
    }
};
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4