husky规范代码提交
# husky规范代码提交
- 当您提交或推送时,您可以使用它来 lint 提交消息、运行测试、lint 代码等。
- Husky 支持所有 Git 钩子。
- husky (opens new window)
# v7.0.0 使用
- 暂不讨论其它版本
- 这个版本和v4不同的区别在于 该版本不需要在
package.json中添加
// package.json 中不需要添加下面代码
"husky": {
"hooks": {
"pre-commit": "npm run test", // 在commit之前先执行npm run test命令
"commit-msg": "commitlint -e $HUSKY_GIT_PARAMS" // 校验commit时添加的备注信息是否符合我们要求的规范
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 安装
npm install husky@7.0.0 -Dnpx husky-init,运行之后会新增一个.husky目录,同时在package.json中的script对象中新增一条"prepare": "husky install"的命令npm install
# 添加 git 钩子
# pre-commit
项目要使用 git 进行代码提交时
npx husky add .husky/pre-commit 'npm run test'- 其实不推荐这种新增的写法,正确写法应该分两步进行,如下:
npx husky add .husky/pre-commit,.husky目录中新增一个pre-commit文件- 修改
pre-commit文件的内容
# pre-commit 文件
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint:fix # 修改这里,上面的内容一般不需要动
1
2
3
4
5
6
2
3
4
5
6
# commit-msg
验证提交信息是否符合规范
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"',经测试,这样会报错;这时应该分两步来完成npx husky add .husky/commit-msg,在.husky目录下新建一个commit-msg文件- 打开
.husky/commit-msg文件修改其内容
# commig-msg 文件
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit $1 # 你要修改的信息
1
2
3
4
5
6
2
3
4
5
6
- 安装commitlint:
npm install @commitlint/cli @commitlint/config-conventional -D - 根目录新增
commitlint.config.js文件,内容如下:
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional']
}
1
2
3
4
5
2
3
4
5
至此就配置好了
上次更新: 2021/09/13, 15:11:59