什么是 commitlint

commitlint 用来校验你提交的信息是否符合规范,它和commitizen很类似,它们都做一件事,那就是让你提交的信息更规范

commitlint 和 commitizen 的区别

commitlint: 校验 git commit 信息是否符合规范(就像 eslint 一样)

commitizen: 辅助 git commit 信息更加规范(就像代码提示一样)

所以你可以把它们两个结合起来使用效果更佳哦~

安装

1
npm install --save-dev @commitlint/config-conventional @commitlint/cli

创建配置文件,可以手动创建,也可以使用命令创建

1
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

然后就会生成commitlint.config.js文件,其中包含module.exports = {extends: ['@commitlint/config-conventional']}代码

这个配置也可以写在package.json文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"name": "study-notes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"prepare": "husky install"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@commitlint/cli": "^16.2.3",
"@commitlint/config-conventional": "^16.2.1",
"husky": "^7.0.4"
},
"commitlint": {
"extends": "@commitlint/config-conventional"
}
}

配合commitizen使用

关于如何使用commitlint可以参考这篇文章: 使用 commitlint 来检查提交的信息是否符合规范

配合husky使用

关于如何使用husky可以参考这篇文章: 使用Husky(哈士奇)管理Git项目

添加hook

1
2
3
4
5
6
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'
# 因为有些命令行不支持上面这条命令
# 如果上面这条对你的项目不管用,可以试试以下其它命令
npx husky add .husky/commit-msg \"npx --no -- commitlint --edit '$1'\"
# 或者
npx husky add .husky/commit-msg "npx --no -- commitlint --edit $1"

测试

不符合规范的提交信息

1
2
3
4
5
6
7
8
9
$ git commit -m "abc"
⧗ input: abc
✖ 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)