npm install eslint --save-dev
npx eslint --init
To check syntax only (構文チェックのみ)
To check syntax and find problems (構文チェックと問題の発見)
To check syntax, find problems, and enforce code style (構文チェック、問題の発見、スタイル強制)
JavaScript modules (import/export)
CommonJS (require/exports)
None of these
React
Vue.js
None of these
Does your project use TypeScript? No / Yes
Browser
Node
How would you like to use ESLint?
でenforce code style
を選択した時のみ
Use a popular style guide
Answer questions about your style
Inspect your JavaScript file(s)
How would you like to use ESLint?
でenforce code style
を選択した時のみ
Airbnb: https://github.com/airbnb/javascript
Standard: https://github.com/standard/standard
Google: https://github.com/google/eslint-config-google
XO: https://github.com/xojs/eslint-config-xo
JavaScript
YAML
JSON
- 質問の回答に合わせて、パッケージの依存関係をdevDependenciesとしてインストールするかどうかを聞かれる
eslint-plugin-react@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^7.12.1 eslint-plugin-import@^2.22.1 eslint-plugin-node@^11.1.0 eslint-plugin-promise@^4.2.1 @typescript-eslint/parser@latest
? Would you like to install them now with npm? No / Yes
# eslintの実行
npx eslint . --ext ts
# exlintの実行後、事項修正
npx eslint . --ext ts --fix
- ESLintプラグインをインストールして使うと便利
"rules": {
"semi": ["error", "always"],
"semi-spacing": ["error", {"after": true, "before": false}],
"semi-style": ["error", "last"],
"no-extra-semi": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error"
}
"rules": {
"semi": ["error", "never", {"beforeStatementContinuationChars": "never"}],
"semi-spacing": ["error", {"after": true, "before": false}],
"semi-style": ["error", "first"],
"no-extra-semi": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error"
}
"rules": {
"object-curly-spacing": [2, "always"]
}
- VSCodeを使っている場合は、プロジェクト内に
.vscode
ディレクトリを生成し、settings.json
に以下の設定をする
{
︙
"eslint.workingDirectories": ["functions"]
︙
}
"rules": {
"indent": [2, 2]
}
- もしくは、三項演算子を使っている箇所で注意文が表示される場合
- indent - ESLint - Pluggable JavaScript Linter
- ESLint v7.0.0 の変更点まとめ - Qiita
- 三項演算子の2項目と3項目のインデントをつける
"rules": {
"indent": ["error", 2, { "offsetTernaryExpressions": true }]
}
if (obj && Object.prototype.hasOwnProperty.call(obj, "key"))
-
関数名になっているところの構文を見直す
-
関数名ではなく、オブジェクトを返そうとしていないか見直す
() => {}
→() => ({})
- バッククォート(`)で囲ったテンプレートリテラルの中で
${}
で式の展開がない記述に関してはシングルクォート(')に変えるようにする - 設定
- クォート表記に関しては、基本的にシングルクォート(')にする
- ただし、エスケープ文字として扱うダブルクォート(")がある場合は、シングルクォート(')に変えない
- テンプレートリテラルを無効化するが、すべてのテンプレートリテラルを禁止するわけではなく、式の展開がない記述だけを対象とする
- allowtemplateliterals
- テンプレートリテラルの使用自体を禁止する場合は、 no-restricted-syntaxでTemplateLiteralセレクターを指定する
"rules": {
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": false }]
}