项目package.json与.git不在同目录时,如何配置husky?
解决Git仓库父目录下项目配置Husky自动Linting的问题
问题背景
项目结构如下:
- Parent Directory - .git - Working Project Directory - node_modules - package.json
为项目配置提交时自动linting,选用husky、eslint、prettier和lint-staged组合,但安装husky时提示找不到.git文件(实际存在于父目录)。尝试过以下方法但无效:
npx mrm lint-staged执行失败(预期情况)- 修改npm prepare脚本为:
"prepare": "cd .. && husky install some-folder/.husky"后执行npm i - 在父目录安装husky,但增加了安装复杂度且效果不佳
错误信息如下:
% npx husky-init && npm install Need to install the following packages: husky-init Ok to proceed? (y) y husky-init updating package.json setting prepare script to command "husky install" /Users/me/.npm/_npx/1ab9c0f68ac2536e/node_modules/husky/lib/index.js:22 throw new Error(`.git can't be found (see ${url})`); ^ Error: .git can't be found (see https://typicode.github.io/husky/#/?id=custom-directory) at install (/Users/me/.npm/_npx/1ab9c0f68ac2536e/node_modules/husky/lib/index.js:22:15) at Object.<anonymous> (/Users/me/.npm/_npx/1ab9c0f68ac2536e/node_modules/husky-init/lib/bin.js:16:21)
可行解决方案
方法1:手动配置Husky,指定Git目录路径
跳过husky-init,手动完成配置:
- 在项目目录(Working Project Directory)下安装依赖:
npm install husky lint-staged --save-dev - 修改项目
package.json中的prepare脚本,明确指定Git目录和husky安装路径(替换实际项目目录名):"scripts": { "prepare": "cd .. && husky install WorkingProjectDirectory/.husky" } - 执行prepare脚本初始化husky:
npm run prepare - 若.husky目录未自动创建,手动生成:
mkdir -p .husky - 添加pre-commit钩子关联lint-staged:
npx husky add .husky/pre-commit "npx lint-staged" - 在
package.json中配置lint-staged规则,示例:"lint-staged": { "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"], "*.{json,md}": ["prettier --write"] }
方法2:通过环境变量指定Git仓库路径
在执行husky命令前,先设置环境变量指向父目录的.git:
- 在项目目录下执行:
export GIT_DIR=../.git - 再运行husky初始化命令:
npx husky-init && npm install - 修改prepare脚本,确保后续安装时能识别Git仓库:
"scripts": { "prepare": "export GIT_DIR=../.git && husky install" }
方法3:调整Git仓库工作目录(推荐)
若项目允许,直接将Git仓库的工作目录设为你的项目目录:
- 进入父目录:
cd .. - 修改Git配置(替换实际项目目录名):
git config core.worktree "./WorkingProjectDirectory" - 返回项目目录,重新执行husky初始化:
此方法让Git直接将项目目录作为工作区,husky可正常识别.git文件。cd WorkingProjectDirectory npx husky-init && npm install
内容的提问来源于stack exchange,提问作者rovac
相关产品推荐
相关产品推荐

