在团队协作开发项目时,如果每个人的提交规范不一致,或者提交时代码有错误,那么在定位 git 提交记录或者 review 代码时将会是一团糟,因此我们可以使用 husky 结合 eslint 来实现 git 提交规范化,保证错误的 commit 不能提交成功。
# commitlint
-
什么是 commitlint
当我们运行
git commit -m 'xxx'
时,commitlint 是用来检查提交信息是否满足固定格式的工具 -
为什么使用 commitlint
团队中规范了 commit 可以更清晰的查看每一次代码提交记录,还可以根据自定义的规则,自动生成 changeLog 文件。
-
commitlint 安装
1
npm install @commitlint/config-conventional @commitlint/cli -D
-
生成配置文件
commitlint.config.js
1
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
文件配置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25'module.exports = {extends: [\'@commitlint/config-conventional\']}'
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', // 新功能
'upd',
'del',
'fix', // 修复bug
'docs', // 文档修改
'style', // 代码格式修改
'refactor', // 代码重构
'test', // 测试用例修改
'chore', // 其他修改, 比如改变构建流程、或者增加依赖库、工具等
'revert', // 回滚到上一个版本
],
],
'subject-full-stop': [0, 'never'],
'subject-case': [0, 'never'],
// 'space-before-function-paren': 0,
},
}
# husky
husky 是 git hooks 工具,作用是对 git 执行的一些命令,通过对应的 hooks 钩子触发,执行自定义的脚本程序
1 | npm install husky --save-dev |
在 package.json 中引入 husky
1 | "husky": { |
这段配置告诉了 git hooks,当我们在当前项目中执行 git commit -m '测试提交'
时将触发 commit-msg
事件钩子并通知 husky,从而执行 commitlint -E HUSKY_GIT_PARAMS
命令,也就是我们刚开始安装的 commitlint,它将读取 commitlint.config.js
配置规则并对我们刚刚提交的测试提交这串文字进行校验,若校验不通过,则在终端输出错误,commit 终止。并且提交时还会触发 pre-commit
命令,执行 eslint 检查。
如果想跳过钩子检查,也可以在 commit 时在后面加上
--no-verify
来跳过,但是并不推荐这样做
# lint-staged
lint-staged
可以让你当前的代码检查只检查本次修改更新的代码lint-staged
无需安装,生成项目时,vue-cli 已经帮我们安装了
需要在 package.json
中添加如下配置,作用是匹配暂存区所有的 js、jsx、vue 文件,并执行命令
1 | "lint-staged": { |
每次它在你本地 commit 之前,校验你所提的内容是否符合你本地配置的 eslint 规则,如果符合规则,则提交成功,如果不符合,则会终止提交,待修复完成后才可提交
# .eslintrc.js
最后附上 eslint 的配置文件,如下:
1 | module.exports = { |