👮♀️
eslintrc で設定できることを理解する記事
今記事は ESLint 公式ドキュメントを紐解きながら、 eslintrc のいろはを理解します
サンプルコード)
eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: "plugin:react/recommended",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: "module",
},
plugins: ["react"],
rules: {
},
};
env
env(environment) は事前定義されているグローバル環境変数を再定義します
よく使う(再定義する)環境変数を以下に示します
- browser ブラウザのグローバル環境変数
- es2021 すべての ECMAScript2021 をグローバルに追加し、 ecmaVersion パーサーオプション ( サポートしたい JavaScript 言語オプションの指定 ) を自動的に 12 (= 2021) に設定します
- node Node.jsグローバル変数とNode.jsスコープ
- jest Jestグローバル変数
- 必要なものだけを有効(true)に設定して使用する
- 今回は
broserとes2021を有効にします
eslintrc.js
env: {
browser: true,
es2021: true,
},
extends
別途参照
parserOptions (構文解析オプション)
parserOptionsは、parserOptionsプロパティを使用して.eslintrc.*ファイルに設定されます。
使用可能なオプションは次のとおりです。
- ecmaFeatures
- ecmaVersion
- sourceType
なお、今記事では後述する内容に基づき、結論として3項目のうち、 sourceType: "module", だけを記述する
以下、実際のコードと各オプションの詳細を示す
例)
eslintrc.js
parserOptions: {
ecmaFeatures: {
// jsx: true,
},
// ecmaVersion: 12,
sourceType: "module",
},
使用する追加の言語機能を示すオブジェクト
globalReturn- グローバルスコープで return ステートメントを許可するimpliedStrictGloabal Strict mode を有効にする(ecmaVersionが5以上の場合)jsx- enable JSX
- React では 基本 JSX を使うので
jsx: true,となるが、外部パッケージeslint-plugin-reactを適用させている場合、ecmaFeatures: {jsx: true,}を内部的に指定していることになるので、 (下記package.json参照)ecmaFeaturesで指定する必要はない
-
ecmaVersion
env: es2021: trueを設定している場合、内容が重複するため、設定する必要はない
以下公式に記述されている仕様
- 使用するECMAScript構文のバージョンを指定可能。
(以下 2021 年時点の内容)- 3、5(デフォルト)、6、7、8、9、10、11、または12に設定可能。
- 2015(6と同じ)、2016(7と同じ)、2017(8と同じ)、2018(9と同じ)、2019(10と同じ)、2020(11と同じ)、または2021(2021と同じ)に設定可能。
- 12)と同じで、年ベースの命名を使用可能。
- 最新のサポートバージョンを使用するように
latestを設定することも可能。
コードがECMAScriptモジュールにある場合は、「script」(デフォルト)または「module」に設定します。
今回は module を使用します
eslintrc.js
sourceType: "module",
plugins
別途参照
## [Quick Fixes](https://code.visualstudio.com/docs/editor/refactoring#_code-actions-quick-fixes-and-refactorings)
エラーを示す波線にカーソルをホバーし、 ⌘. を入力すると Quick Fixes が表示され、 Disable (無効化)する方法を選択できるようになります

<br/>
- `disable ** for this line` を選択
以下のような内容が表示され、1行だけ Disable することができます
// eslint-disable-next-line react/prop-types
<br/>
- `disable ** for the entire file` を選択
以下のような内容が表示され、ファイル全体で Disable することができます
/* eslint-disable react/prop-types */
<br/>
- `show documantation for **`
rule の document を確認できます
今回の設定例)
```js: eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ["plugin:react/recommended"],
parserOptions: {
sourceType: "module",
},
plugins: [],
rules: {
"react/react-in-jsx-scope": "off",
"react/prop-types": "off",
},
};
Discussion