是否必须执行npx husky init使husky钩子生效?如何简化项目使用流程?
解决方案
要实现用户克隆项目、安装依赖后直接触发提交校验,无需手动执行npx husky init,可以通过以下步骤配置:
步骤1:在你的项目中预先配置husky钩子并提交到仓库
- 在本地项目中执行
npx husky init生成.husky目录 - 添加commitlint的钩子脚本:
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"' - 处理
pre-commit钩子(如果不需要该钩子的校验逻辑,保留空文件即可,如你之前的操作echo "" > .husky/pre-commit) - 确保
.gitignore文件中没有忽略.husky目录,然后将整个.husky目录提交到GitHub仓库
步骤2:在package.json中添加prepare生命周期脚本
在项目的package.json中添加如下脚本:
{ "scripts": { "prepare": "husky install" } }
原理说明
prepare是npm的内置生命周期脚本,当用户执行npm i时,该脚本会自动运行,帮用户完成husky install的操作——也就是初始化husky并启用仓库中已提交的钩子配置。这样用户克隆项目后,只需要执行npm i,后续提交代码时就能自动触发commitlint的校验。
验证效果
完成上述配置后,用户执行以下命令就能直接触发校验:
git clone git@github.com:fireflysemantics/fs-github-flow-docs-starter.git cd fs-github-flow-docs-starter/ npm i git add . && git commit -m "linting error"
此时会输出你预期的校验失败提示:
⧗ input: linting error ✖ subject may not be empty [subject-empty] ✖ type may not be empty [type-empty] ✖ found 2 problems, 0 warnings ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint husky - commit-msg script failed (code 1)
内容的提问来源于stack exchange,提问作者Ole
相关产品推荐
相关产品推荐

