LoginSignup
5
6

More than 5 years have passed since last update.

緩く始める ESLint による静的解析と prettier によるコードフォーマット in React

Posted at

目的はとりあえず最低限の静的解析とそれに準じたフォーマットを施す環境を作ること。
対象ユースケースは React を用いたフロントエンド開発。
こだわる場合は時間の無駄になるので読まない方が良いです。

各々の概要は公式ドキュメントを参照されたし

$ cd ${your_project}
$ touch .eslintrc.json
$ npm install eslint eslint-plugin-react prettier-eslint-cli --dev

.eslintrc.json を次のように編集

eslintrc.json
{
  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": ["react"],
  "rules": {
    "indent": ["error", 2],
    "linebreak-style": ["error", "unix"],
    "quotes": ["error", "single"],
    "semi": ["error", "always"],
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error"
  }
}

例えば /src に js ファイルを格納している場合

$ ./node_modules/.bin/prettier-eslint --write ./src/**/*.js

おまけ VSCode 設定

まずは VSCode 拡張である二つをインストールする

あとは以下を設定するだけで作業中のディレクトリに eslint の設定ファイル(例 .eslintrc.json)があればその設定を読み込んで静的解析とフォーマットをしてくれる。

settings.json
  "editor.formatOnSave": true,
  "prettier.eslintIntegration": true,

個人的には VSCode のJS標準フォーマッタがたまに壊れるのにフラストレーションが溜まっていたのが設定の動機。
ESLint の設定は今後チューニングしていくかもしれないが、とりあえずこれでほとんどの場合快適にいけるのではと思う。
快適。

参考記事

5
6
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
5
6