0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

モノレポでhusky & lint-stagedが効かない場合の原因と対処法

Last updated at Posted at 2025-10-10

うまくいかなかったのでメモ。

結論

公式ドキュメントを読もう。
https://typicode.github.io/husky/how-to.html#project-not-in-git-root-directory

英語ドキュメントが辛い方

翻訳しよう。

以上です。


トップディレクトリがmyappfrontendディレクトリ配下のファイルのコミットでESLintやprettierを実行する場合。

frontendディレクトリからリポジトリのルート(mypage)に対してHuskyの設定を行うのがポイント。


設定の手順

すべての操作はmypage/frontendディレクトリ内で行います。

1. 必要なパッケージをインストール

まず、frontendディレクトリに必要な開発者向けパッケージをすべてインストールします。

# mypage/frontend ディレクトリにいることを確認
cd /path/to/mypage/frontend

# 必要なパッケージをまとめてインストール
npm install --save-dev husky lint-staged eslint prettier

2. frontend/package.json を設定

mypage/frontend/package.jsonに、Huskyを有効化するためのスクリプトと、lint-stagedの具体的な設定を追記します。

mypage/frontend/package.json
{
  // ... 他の設定
  "scripts": {
    // ... 他のスクリプト
    "prepare": "cd .. && husky install"
  },
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}
  • "prepare": "cd .. && husky install" の意味:
    • preparenpm installが実行された後などに自動で実行されるスクリプトです。
    • cd ..で一時的に親ディレクトリ(mypage)に移動します。
    • husky installを実行し、リポジトリのルートに.huskyディレクトリを作成してGitフックを有効化します。

3. npm install を再度実行

prepareスクリプトを一度実行させるために、npm installをもう一度実行します。

# mypage/frontend ディレクトリで実行
npm install

このコマンドが成功すると、リポジトリのルートであるmypageディレクトリに.huskyディレクトリが作成されているはずです。

4. コミットフックを追加

次に、コミット前に実行したいコマンドをHuskyに登録します。このコマンドもfrontendディレクトリから実行します。

# mypage/frontend ディレクトリで実行
npx husky add ../.husky/pre-commit "npx lint-staged"
  • このコマンドの意味:
    • ../.husky/pre-commitというパスを指定して、リポジトリルートにあるpre-commitフックファイルを作成・編集します。
    • 実行するコマンドとして"npx lint-staged"を登録します。

【重要】 lint-stagedはpackage.jsonがある場所(今回はfrontend)で実行される必要があるため、上記コマンドで登録されたフックスクリプトを少し修正します。

mypage/.husky/pre-commit ファイルを開き、以下のように cd frontend の一行を追加してください。

mypage/.husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# frontendディレクトリに移動してからlint-stagedを実行
cd frontend
npx lint-staged

これで、トップディレクトリにpackage.jsonを置くことなくfrontendディレクトリの管理下でhuskyとlint-stagedを導入できました!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?