前提
- webpack実行時に、eslintでコードチェックできるようにする
- webpackの基本的な構築方法は省略
- TypeScriptではなく、ネイティブのJavaScriptにて構築
- React環境にて構築
インストールするライブラリ
- eslint
- eslint-loader
- babel-eslint
eslintの初期化
- 下記コマンドを実行
npx eslint --init
- 下記質問が表示されるので、指定したものを選択
// syntaxとstyleについてのチェックするを選択
? How would you like to use ESLint?
To check syntax only
To check syntax and find problems
❯ To check syntax, find problems, and enforce code style
// import/exportが主流なのでこちらを選択
? What type of modules does your project use? (Use arrow keys)
❯ JavaScript modules (import/export)
CommonJS (require/exports)
None of these
// TypeScriptを使用する場合はy,使用しない場合はN
// 今回はNo
Does your project use TypeScript? (y/N)
// どのjsフレームワークを使用するか?
// 今回はReactを使用する
? Which framework does your project use?
❯◉ React
◯ Vue
◯ None of these
// ブラウザで動作するアプリケーションを前提としているので以下を選定
? Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Browser
◯ Node
// どれでも良いが、シェアの高いAirbnbを選定
? Which style guide do you want to follow? (Use arrow keys)
❯ Airbnb: https://github.com/airbnb/javascript
Standard: https://github.com/standard/standard
Google: https://github.com/google/eslint-config-google
// .eslintrsファイルの形式を選択
// jsonを選んだ場合、json形式になる(.eslintrc.json)
? What format do you want your config file to be in?
JavaScript
YAML
❯ JSON
// 関連するライブラリをinstallするか?
// yesを選択
Would you like to install them now with npm? (Y/n)
- 上記設定を選択すると、「.eslintrc.json」ファイルが生成される
{
"env": {
"browser": true,
"es2020": true
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 11,
"sourceType": "module"
},
"plugins": ["react"],
"rules": {}
}
webpackの設定
// rulesの中に記載されたloaderは、後ろから順番に実行される
// 1番最初に記述したloaderは最後に実行される
// 順番を入れ替えるのが面倒なため、「enforce」の設定を記載する
rules: [
{
// enforce:preを持たないruleよりも早く実行される (1番最初に実行される)
enforce: 'pre',
// eslintの対象は記述子が.jsまたは.jsxのファイルのみ
test: /\.jsx?$/,
// /node_modules/をeslintの対象から外す
exclude: /node_modules/,
loader: 'eslint-loader',
},
]
babel-eslintの設定
- eslintrs.jsonにbabel-eslintを設定
{
"env": {
"browser": true,
"es2020": true
},
// parserを追記
"parser": "babel-eslint",
}
eslintを実行
- webpackコマンド実行時にeslintが走る
npx webpack
- または eslintコマンドで対象のファイルを指定して実施する
npx eslint [対象のファイル名]
エラー解消
jsxの記述子しかeslintしないエラー
- Airbnbのスタイルガイドでjsxの記述子しかeslintできない仕様になっている
- エラー内容
src/App.js|8 col 7 error| JSX not allowed in files with extension '.js' (react/jsx-filename-extension)
- 無視する場合は、.eslintrc.jsonに以下の設定を記載
{
"env": {
"browser": true,
"es2020": true
},
//こちらを追記
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }]
}
}
eslint実行時にエラーになる
- npx webpackコマンド実行時に、eslintでエラーになる場合
- 以下のメッセージがある場合は、コマンド実行によって自動で修正できる
✖ 2 problems (2 errors, 0 warnings)
2 errors and 0 warnings potentially fixable with the `--fix` option.
- こちらのコマンドで自動で修正できる
npx eslint --fix [対象のファイル]