npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
.eslintrc.json
にルールを追加以下のように設定してください:
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": ["plugin:@typescript-eslint/recommended"],
"rules": {
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "variable",
"types": ["boolean"],
"format": ["camelCase"],
"custom": {
// `is`, `has`, `can` で始まることを強制
"regex": "^(is|has|can)[A-Z]",
"match": true,
},
},
],
},
}
// ✅ OK
const isVisible = true
const hasPermission = false
const canSubmit = true
// ❌ NG(ESLintエラーになります)
const visible = true
const permission = false
const flag = true
types: ["boolean"]
を指定することで 型情報に基づいた検出 を行うため、必ず @typescript-eslint/parser
を使ってください。parserOptions.project
に tsconfig.json
を指定するのも効果的です:"parserOptions": {
"project": "./tsconfig.json"
}
ただしこれはESLintに型チェックをさせるためビルドがやや重くなります。
npx eslint src/**/*.ts
true
/false
で初期化されていない変数は型推論されない可能性があるので注意!const maybeBool = someFunc() // 戻り値がbooleanであることが型推論されなければルール対象外になる
こういう場合は、型アノテーションをつけておくとルールが正しく適用されます。
Next.js プロジェクトで、すべての .ts
/ .tsx
ファイルに ESLint の静的解析を適用する方法を手順付きでまとめます。
.eslintrc.json
の設定tsconfig.json
の確認eslint
実行方法Next.js 公式の ESLint セットアップを使用します:
npx next lint
このコマンドを実行すると、以下のパッケージが自動でインストールされ、.eslintrc.json
が生成されます:
eslint
eslint-config-next
.eslintrc.json
に TypeScript の命名規則ルールを追加生成された .eslintrc.json
に以下を追加してください:
{
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/naming-convention": [
"error",
{
"selector": "variable",
"types": ["boolean"],
"format": ["camelCase"],
"custom": {
"regex": "^(is|has|can)[A-Z]",
"match": true,
},
},
],
},
}
tsconfig.json
の確認(必要なら parserOptions
に指定).eslintrc.json
に以下を追加して、ESLint が型情報を正しく解析できるようにします:
"parserOptions": {
"project": "./tsconfig.json"
}
その際、ESLint が型情報を必要とするため、tsconfig.json
には "include"
に src
フォルダなどを明示しておくとよいです:
{
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"],
}
.eslintignore
をチェック(必要なら調整).eslintignore
に以下のような除外があると、チェック対象から外れてしまうので注意してください:
node_modules
.next
public
↑ .ts
や .tsx
を除外していないことを確認
.ts
, .tsx
をチェックする実行コマンドプロジェクトルートで以下を実行してください:
npx eslint . --ext .ts,.tsx
または、次のように package.json
にスクリプトを追加:
"scripts": {
"lint": "eslint . --ext .ts,.tsx"
}
実行:
npm run lint
.vscode/settings.json
に以下を入れると、保存時に自動で ESLint チェックが走ります:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
},
}
eslint
, @typescript-eslint/*
パッケージがインストール済み.eslintrc.json
に @typescript-eslint/naming-convention
が設定済みnpx eslint . --ext .ts,.tsx
で全ファイルチェック可能.eslintignore
で .ts
, .tsx
が除外されていない準備は以上です!
もし match: true
→ match: false
にして、「禁止したい命名パターンがある」場合に変更も可能なので、ルール強化もお気軽にご相談ください。