ESLint
https://eslint.org/
JavaScript や TypeScript、jsx のための 静的解析ツール
React は Angular、Jest 用のプラグインも存在する
Jest: https://github.com/jest-community/eslint-plugin-jest
コードの品質と コードスタイル をチェックする
文法的には正しいが、間違いを含む可能性のあるコードを検出する
e.g. = と ==(===)
code:js
if (savings = 0) {
}
JavaScript の実行時エラーも事前に気がつける
e.g. window を wisdom と タイポ
導入
warning.icon v9.0 から Flat Config がデフォルトになった
typescript-eslint もサポート済み
https://eslint.org/docs/latest/use/getting-started
コマンド
code:sh
$ npm init @eslint/config
Need to install the following packages:
@eslint/create-config@1.3.1
Ok to proceed? (y) y
以下の質問に答える
How would you like to use ESLint?
To check syntax only
To check syntax and find problems
What type of modules does your project use?
JavaScript modules (import/export)
CommonJS (require/exports)
None of these
Which framework does your project use?
React
Vue.js
None of these
Does your project use TypeScript ?
No
Yes
Where does your code run?
Browser
Node
Would you like to install them now?
Yes
No
Which package manager do you want to use? …
npm
yarn
pnpm
bun
インストール完了後、選択肢を元に設定ファイルが作成されるので、必要に応じてカスタマイズする
https://eslint.org/docs/latest/use/configure/
code:eslint.config.js
const pluginJs = require("@eslint/js");
const pluginJest = require("eslint-plugin-jest");
/** @type {import('eslint').Linter.Config[]} */
module.exports = [
pluginJs.configs.recommended,
{
...pluginJest.configs"flat/recommended",
files: "*.test.js",
},
{
languageOptions: {
sourceType: "commonjs",
},
},
ignores
];
除外したいディレクトリは ignores で指定可能
https://eslint.org/docs/latest/use/configure/ignore
code:eslint.config.js
export default [
{
ignores: ".config/*"
}
];
実行
https://eslint.org/docs/latest/use/command-line-interface#run-the-cli
code:sh
$ npx eslint
--fix オプションを付けると、自動的に修正可能な問題を修正してくれる
https://eslint.org/docs/latest/use/command-line-interface#--fix
code:sh
$ npx eslint --fix
package.json の scripts への追加
code:package.json
{
"scripts": {
"test": "jest",
"lint": "eslint . && prettier --list-different .",
"format": "eslint --fix && prettier --loglevel warn --write ."
},
}
Visual Studio Code との統合
以下の拡張機能をインストールすると、コマンドを実行すること無く自動でチェックが走るようになる
https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint
Tips
入力終わる前に Linter が警告を発するため、偽陽性 が多く発生する
もしこれが気になる場合は、以下のように保存時のみ動作するように設定すれば良い
code:json
{
...
"eslint.run": "onSave",
...
}
Prettier との衝突を避ける
ESLint と Prettier との設定が衝突するのを避けるためには、eslint-config-prettier プラグインを追加する
https://github.com/prettier/eslint-config-prettier
Prettier 公式から提供されている
e.g.
code:eslint.config.js
const eslintConfigPrettier = require("eslint-config-prettier");
/** @type {import('eslint').Linter.Config[]} */
module.exports = [
pluginJs.configs.recommended,
eslintConfigPrettier,
...
]
代替
xo: https://github.com/xojs/xo