在我们的项目中,尽管已经引入了prettier和eslint来校验代码格式,但在多人协作开发时,仍然难以避免有人提交不符合规范的代码到仓库中。这不仅增加了我们拉取代码后需要手动修改的时间成本,还可能导致代码风格不统一的问题。为了解决这些问题,我们可以引入husky工具,从源头上规范代码提交流程。
具体来说,husky是一个Git Hooks工具,它可以在我们执行git commit等操作之前,自动运行一系列预定义的脚本或命令。通过配置husky,确保提交的代码符合项目规范。此外,husky还可以通过commit-msg钩子来规范提交信息的格式,避免团队成员提交五花八门的commit message。
以下是husky的具体使用步骤:
1.commitlint安装依赖:
npm install --save-dev @commitlint/cli
npm install --save-dev @commitlint/config-conventional
2.创建 commitlint.config.js 文件
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-case': [2, 'always', ['lower-case', 'upper-case']],
'type-enum': [2, 'always',[
'feat', // 增加新功能
'fix', // 修复问题/BUG
'style', // 代码风格相关无影响运行结果的
'perf', // 优化/性能提升
'refactor', // 重构
'revert', // 撤销修改
'test', // 测试相关
'docs', // 文档/注释
'chore', // 依赖更新/脚手架配置修改等
'workflow', // 工作流改进
'ci', // 持续集成
'types', // 类型定义文件更改
'wip', // 开发中
'undef' // 不确定的分类
]
]
}
}
3.husky安装依赖:
npm install husky@7.0.1 --save-dev
启动 hooks , 生成 .husky 文件夹
npx husky install
4.在 package.json 中生成 prepare 指令
npm set-script prepare "husky install"
执行 prepare 指令
npm run prepare
5.添加 commitlint 的 hook 到 husky中,
npx husky add .husky/commit-msg
找到.husky文件下 commit-msg文件 添加指令
npx --no-install commitlint --edit "$1"
至此, 不符合规范的 commit 将不再可提交:
sql 代码解读复制代码git commit -m "test"
⧗ input: test
✖ 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 hook exited with code 1 (error)
那么至此,我们就已经可以处理好了 强制规范化的提交要求,到现在 不符合规范的提交信息,将不可在被提交!
6.正确提交
git commit -m "feat: xxx"
git commit -m "fix: xxx"