husky
是一个 Git Hooks 管理工具,它的主要作用是 在 Git 提交(commit)、推送(push)等操作时执行自定义脚本,比如代码检查(Lint)、单元测试(Test)、格式化代码(Prettier)等。
📌 husky
的作用
- 强制代码规范:在
pre-commit
钩子执行eslint
,确保提交的代码符合规范。 - 自动格式化代码:结合
prettier
在pre-commit
里自动格式化代码,避免手动修改格式。 - 防止提交 Bug:在
pre-push
执行单元测试 (npm test
),如果测试未通过,禁止推送。 - 自动执行脚本:可以用 Git 钩子自动运行
build
、deploy
、update
等脚本。
🎯 husky
的常见 Git Hooks
Git Hook | 触发时机 | 作用 |
---|---|---|
pre-commit | git commit 之前 | 运行 eslint 、prettier 、检查代码 |
commit-msg | git commit 之后 | 规范化提交信息(如 feat: xxx ) |
pre-push | git push 之前 | 运行 npm test ,防止推送有 Bug 的代码 |
pre-rebase | git rebase 之前 | 确保变基不会出错 |
post-merge | git pull 之后 | 自动安装依赖 npm install |
✅ husky
的使用
1️⃣ 安装 husky
npx husky-init && npm install
或者手动安装:
npm install husky --save-dev
然后启用 Git Hooks:
npx husky install
2️⃣ 添加 pre-commit
钩子
npx husky add .husky/pre-commit "npm run lint"
这样,每次 git commit
时,都会执行 npm run lint
进行代码检查。
3️⃣ 添加 pre-push
钩子
npx husky add .husky/pre-push "npm test"
这样,每次 git push
时,都会执行 npm test
运行单元测试,如果测试失败,推送会被阻止。
📢 什么时候应该用 husky
?
✅ 适合团队合作、多人开发,强制代码规范。
✅ 适合大型项目,避免提交低质量代码。
❌ 如果是个人项目,且没有严格代码规范,可以不装 husky
。
🚀 如果想要移除husky
有些个人开发者不需要很强的代码规范,新接手一些轮子的时候可能会遇到 git commit
报错,是因为 husky
在 pre-commit
阶段执行 npm test
,但你的 package.json
里 没有 test
脚本,导致错误。
解决方案:
假设 husky 是你项目中的一个依赖包,你可以通过以下步骤使用 Yarn 将其移除:
- 在项目根目录下运行以下命令:
yarn remove husky
- 这会同时:
- 从 package.json 中删除 husky 的依赖记录
- 删除 node_modules 中相关的 husky 文件
- 如果你之前配置了 husky 的钩子(hooks),你可能还需要:
- 检查 .git/hooks 目录,删除相关的钩子文件
- 或者直接删除 .husky 目录(如果存在)
示例完整操作:
# 移除 husky 包
yarn remove husky# 如果需要,删除 husky 配置目录
rm -r -fo .husky
完成后,你可以用以下命令验证 husky 是否已移除:
yarn list --pattern husky
如果返回空结果,说明 husky 已成功移除。
或者
npm uninstall husky
rm -rf .husky
然后重新提交代码。
你可以看看 husky
的 pre-commit
里到底执行了什么:
cat .husky/pre-commit