フォーマッター設定
Prettierのインストール
Prettierをインストールします。
npm i -D prettier
Prettierの設定
.prettierrc
{
"tabWidth": 2,
"printWidth": 100,
"semi": true,
"singleQuote": true,
"bracketSpacing": true,
"bracketSameLine": true,
"trailingComma": "all",
"arrowParens": "always"
}
.prettierignoreの設定
lock ファイルなどを指定
.prettierignore
node_modules
.next
.gitignore
.eslintignore
.prettierignore
フォーマット用のコマンド
npm-scriptsにフォーマットのためのコマンドを追加
"scripts": {
...
+ "prettier": "prettier --write ."
},
ESLintの推奨ルールを設定
ESLint本体の推奨ルールセットを追加
.eslintrc.jsonを修正
{
- "extends": "next/core-web-vitals"
+ "extends": ["eslint:recommended", "next/core-web-vitals"]
}
TypeScriptに関するルールの追加
TypeScript用のESLintルール typescript-eslint を追加
@typescript-eslint/parser
TypeScriptの構文を解析するパーサー@typescript-eslint/eslint-plugin
Typescript用のESLintプラグイン(推奨ルールセットもここに含まれている)
npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
.eslintrc.jsonを修正
{
"extends": [
"eslint:recommended",
+ "plugin:@typescript-eslint/recommended-type-checked",
"next/core-web-vitals"
],
+ "parser": "@typescript-eslint/parser",
+ "parserOptions": {
+ "project": "./tsconfig.json"
}
}
Prettierと衝突するルールを無効化
ESLintでフォーマットに関するルールを設定していると、Prettierと競合するルールがあるため、回避するルールを追加。
npm i -D eslint-config-prettier
.eslintrc.jsonを修正
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended-type-checked",
"next/core-web-vitals",
+ "prettier"
],
Husky & lint-staged
Huskyとlint-stagedを使ってGitのコミット前にコードチェックを実行し、問題のあるコードがコミットされないような環境を設定。
- Husky
Gitのコミットやプッシュ実行時に処理を呼び出すツール
(ここではpre-commitフックの際にlint-stagedを呼び出します) - lint-staged
Gitでステージされたファイルに対して処理を呼び出すツール
Huskyとlint-stagedのインストール
パッケージをインストール
npm i -D husky lint-staged
Husky の初期化と設定
Huskyの初期化と設定ファイルの作成
npx husky init
.husky/pre-commitを修正
- npm run test
+ npx lint-staged
lint-staged の設定
プロジェクトルートに .lintstagedrc.js を作成
以下参考
https://nextjs.org/docs/pages/building-your-application/configuring/eslint#lint-staged
const path = require("path");
const buildEslintCommand = (filenames) =>
`next lint --fix --file ${filenames
.map((f) => path.relative(process.cwd(), f))
.join(" --file ")}`;
module.exports = {
"*.{js,cjs,mjs,json,ts,tsx,css}": ["prettier --write"],
"*.{ts,tsx}": [buildEslintCommand],
};