2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】Husky と lint-staged でコミット前に ESLint と Prettier を実行する

Last updated at Posted at 2024-08-25

はじめに

この記事では、Next.js 環境において Husky と lint-staged を利用してコミット前に ESLint と Prettier を実行する手順を記載します。

Husky とは

  • Git hooks を簡単に管理するためのツール
  • コード品質を担保するために利用される
  • Git hooks とは、Git ワークフロー(コミット前後、プッシュ前など)で実行されるスクリプト

lint-staged とは

  • Git でステージ上の(変更された)ファイルに対してスクリプトを実行するためのツール

開発環境

開発環境は以下の通りです。

  • Windows 11
  • Next.js 14.2.4
  • React 18.3.1
  • TypeScript 5.5.2
  • Husky 9.1.5
  • lint-staged 15.2.9
  • ESLint 8.57.0
  • Prettier 3.3.3

Husky と lint-staged のインストール

まずは Husky と lint-staged のインストールします。

npm install --save-dev husky lint-staged

Husky の初期化

Husky の初期化コマンドを実行します。

npx husky init

実行後、以下2点が追加されます。

  • "prepare": "husky" スクリプトの追加
  • .husky フォルダの追加

"prepare": "husky" スクリプトの追加

package.jsonscripts"prepare": "husky" が追加されます。

package.json
{
  ...,
  "scripts": {
    ...,
    "prepare": "husky"
  },
  ...
}

preparenpm install 前に自動で実行されます。

.husky フォルダの追加

.husky フォルダ内には pre-commit ファイルと _ フォルダが含まれています。pre-commit の中身は以下の通りです。

npm

pre-commit で lint-staged を実行するために中身を書き換えます。

npx lint-staged

lint-staged の設定

package.json"lint-staged" を追加して、ESLint と Prettier を実行するスクリプトを記載します。

package.json
{
  ...,
  "lint-staged": {
    "src/**/*.{ts,tsx,json,css,scss}": [
      "prettier --write",
      "next lint --fix --dir src"
    ]
  }
}

以上で設定完了です。

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?