在我们团队协作开发时,如果每个人的git的commit提交规范都不一样,最后的代码review或看git的log提交记录时就是一团乱,今天我们用commit + husky实现git提交规范化,保证错误的commit信息不能提交成功。
一、在项目中安装commitlint
- 安装依赖
npm install --save-dev @commitlint/{cli,config-conventional}
- 生成配置文件
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
commitlint
是检测我们提交的规范的,具体规范如下:
type(scope?): subject
body?
footer?
其中type
和subject
是必需的,其他是可选的,type 用于说明 commit 的类别,也可以自己在配置文件中更改或者扩展。subject是 commit 目的的简短描述,不能超过50个字符,且结尾不加英文句号。
type的类型如下:
feat:新功能(feature)
fix:修补bug
docs:文档(documentation)
style: 格式方面的优化
refactor:重构
test:测试
chore:构建过程或辅助工具的变动
二、在项目中安装husky
husky
能够实现 git hooks ,就是在我们使用 git 命令的时候,执行一些操作等,如这里就是在 git commit 时执行commitlint规范检测。
- 安装依赖
npm install --save-dev husky
- 在
package.json
中配置
// package.json
{
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
三、最后我们来项目中测试下
$ git commit -m "add: first"
husky > commit-msg (node v12.16.2)
⧗ input: add: first
✖ type must be one of [build, chore, ci, docs, feat, fix, improvement, perf, refactor, revert, style, test] [type-enum]
✖ found 1 problems, 0 warnings
ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
husky > commit-msg hook failed (add --no-verify to bypass)
执行了
git commit -m "add: first"
但其实它并不符合我们 commitlint 的规范,所以并没有通过,报错了,到此 commitlint 的使用就完成了,看完的小伙伴记得动手操作一遍哦,有不懂得也可以留言哦!