LoginSignup
42
43

More than 5 years have passed since last update.

ESLint で ES6で書かれたReact のコードを検証する

Posted at

やりたいこと

ES6で書かれた、Reactのコードを静的に検証したい。

この記事では、ESLint を使った例を紹介します。
以下の例は全てESLint v3.1.1 で実行しました。

インストール

eslint, eslint-plugin-react モジュールを、local にインストールします。

$ npm install eslint --save-dev
$ npm install eslint-plugin-react --save-dev

設定ファイル(.eslintrc)を作成する

手動で設定ファイルを作成してもOKですが、eslint には設定ファイルを自動生成するコマンドがあるので、今回はこれを使います。

プロジェクトのルートディレクトリで
node node_modules/eslint/bin/eslint --init を実行すると、例1が表示されます。

例1

$ node node_modules/eslint/bin/eslint --init
? How would you like to configure ESLint?
❯ Answer questions about your style
  Use a popular style guide
  Inspect your JavaScript file(s)

今回は、一番上の[Answer questions about your style] を選択し、wizard 形式で設定ファイルを作成します。例2の質問に y/N で答えていくと、カレントディレクトリに .eslintrc.json ファイルが生成されます。

例2

? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser
? Do you use CommonJS? No
? Do you use JSX? Yes
? Do you use React Yes
? What style of indentation do you use? Spaces
? What quotes do you use for strings? Double
? What line endings do you use? Unix
? Do you require semicolons? No
? What format do you want your config file to be in? JSON

生成された設定ファイルはこちらです。

eslintrc.json
{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "indent": [
            "error",
            4
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "never"
        ]
    }
}
  • rules プロパティに、先ほどの質問の答えに沿ったルールが設定されています。

  • extends プロパティに "eslint:recommended" が指定されています。
    これにより、ESLintがデフォルトで推奨するルールが適用されます。適用されるルールは、こちらのリストの、チェックがついているルールです。

eslint-plugin-react の recommened rulues を適用する

設定ファイルの extends プロパティに、eslint-plugin-react が提供している 推奨ルールを設定します。

eslintrc.json
...
"extends": ["eslint:recommended", "plugin:react/recommended"],
...

この設定で適用されるルールについては、下記を参照してください。
https://github.com/yannickcr/eslint-plugin-react#recommended-configuration

個別のruleを調整

プロジェクトに合わせて、rules プロパティを修正していきます。

eslintrc.json
...
"rules": {
        "indent": [
          "error",
          2,
          {"SwitchCase": 1}
         ],                            //インデントをスペース2個に変更, switch文にも indent を適用
        "no-console": "off",           //no-console ルールを off
        "react/no-set-state": "error", //react/no-set-stateルールを適用
        ...
}
...

recommened 以外にもたくさんのルールがあるので、少しずつ試しながら、プロジェクトに合ったルールセットを作っていきます。また、Airbnb などのサービスが公開しているShareable Config (共有設定)を適用するのも良いでしょう。

ESLint の ルールリスト
http://eslint.org/docs/rules/

eslint-plugin-react のルールリスト
https://github.com/yannickcr/eslint-plugin-react#list-of-supported-rules

Airbnb の 共有設定
https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb

実行

手動でeslintコマンドを実行するのは面倒なので、実行を自動化します。

package.json に登録

(対象 path はプロジェクトに合わせて修正してください)

package.json
  ...
  "scripts": {
    "lint": "eslint ./js/**/*.js"
  },
  ...
$ npm run lint

gulp タスクとして登録する

task runner に gulpを使っている場合は、task として設定できます。
npm install gulp-eslint --save-dev

gulpfile.js
const gulp = require('gulp');
const eslint = require('gulp-eslint');

gulp.task('lint', () => {
  return gulp.src(['js/**/*.js','!node_modules/**'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

$ gulp lint

コードの修正

ルールに違反する記述があると、下記のように出力されます。

~/eslint_example/js/actions/SampleActions.js
   9:7  error  Extra semicolon  semi
  11:2  error  Extra semicolon  semi

ファイル名と行番号が出力されているので、手動で修正していきます。
もしくは、こちらのリストで レンチのアイコンがついているルールは、--fix オプションをつけてeslint コマンドを実行すると、自動修正してくれます。

package.json
  ...
  "scripts": {
    "lint": "eslint ./js/**/*.js",
    "auto_fix": "eslint --fix ./js/**/*.js"
  },
  ...
$ npm run auto_fix

参照させていただいた記事

42
43
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
42
43