通过设置git hooks, 强制统一团队的git提交信息格式;
1.安装husky、commitlint(cli,config),lint-staged
husky: 使git hook配置能与团队成员共享
commitlint:对提交信息格式进行校验
npm isntall --save-dev @commitlint/config-conventional @commitlint/cli
lint-staged: 过滤文件,使执行的命令只作用在暂存区的文件
2.添加自定义config
在项目根目录添加commitlint.config.js
module.exports = {
extends: [
"@commitlint/config-conventional"
],
rules: {
'subject-case': [0]
},
};
由于commitlint中间有过重大的版本(version>1)更改,所以使用方式有很大差异, 注意git版本应跟随变化
husky requires now Git `>= 2.13.2`. If you're already using husky `v2` and don't use an old version of Git, you can safely upgrade.
老版本husky的使用
3.添加package.json
"scripts":{
"test": "commitlint -e", //用于测试是否成功
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
"lint-staged": {
"src/**/*.{js,vue}": [
"eslint --fix",
"git add"
]
},
4. 测试是否成功
修复文件,运行: git commit -m 'sfdsf',应该提示错误
报错
- commit message找不到 (./.git/COMMIT_EDITMSG)
throw err;
^
Error: Received 'HUSKY_GIT_PARAMS' as value for -E | --env, but environment variable 'HUSKY_GIT_PARAMS' is not available globally可能因为版本的缘故,commit-msg命令的入参不存在,(详情查看commitlint --help)。
解决: 修改入参名称为,"commit-msg": "commitlint -e" (自动获取commit message)
2. 设置的hook无效,未执行
有可能hookPath设置的路径有误
解决:git config core.hooksPath .git/hooks
注意: The `core.hooksPath` support is [new in Git version 2.9](https://github.com/git/git/blob/master/Documentation/RelNotes/2.9.0.txt#L127-L128), having been put in with [commit `867ad08a2610526edb5723804723d371136fc643`](https://github.com/git/git/commit/867ad08a2610526edb5723804723d371136fc643). If your Git version is not at least 2.9.0, setting a hooks-path variable will have no effect at all.
高版本的husky
3.添加package.json
"scripts":{
"lint-staged": "lint-staged",//无用,只是用于手动测试
},
"lint-staged": {
"src/**/*.{js,vue}": [
"eslint --fix",
"git add"
]
},
4. 添加hooks执行命令
npx husky install // 初始化husky,生成.husky文件夹
npx husky add .husky/pre-commit "npx --no-install lint-staged"
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
分别得到文件 .husky/pre-commit和.husky/commit-msg文件
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1"
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install lint-staged
注意:如果执行后,没有成功,可手动创建
总结
可以看出,新版本的用法更清晰灵活