我们了解了 git hooks
的概念,那么接下来我们就使用 git hooks
来去校验我们的提交信息。
要完成这么个目标,那么我们需要使用两个工具:
-
commitlint:用于检查提交信息
-
husky:是
git hooks
工具
注意:npm
需要在 7.x 以上版本!!!!!
那么下面我们分别来去安装一下这两个工具:
commitlint
-
安装依赖:
npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4
-
创建
commitlint.config.js
文件echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
-
打开
commitlint.config.js
, 增加配置项( config-conventional 默认配置点击可查看 ):module.exports = { // 继承的规则 extends: ['@commitlint/config-conventional'], // 定义规则类型 rules: { // type 类型定义,表示 git 提交的 type 必须在以下类型范围内 'type-enum': [ 2, 'always', [ 'feat', // 新功能 feature 'fix', // 修复 bug 'docs', // 文档注释 'style', // 代码格式(不影响代码运行的变动) 'refactor', // 重构(既不增加新功能,也不是修复bug) 'perf', // 性能优化 'test', // 增加测试 'chore', // 构建过程或辅助工具的变动 'revert', // 回退 'build' // 打包 ] ], // subject 大小写不做校验 'subject-case': [0] } }
注意:确保保存为 UTF-8
的编码格式,否则可能报错。
husky
-
安装依赖:
npm install husky@7.0.1 --save-dev
-
启动
hooks
, 生成.husky
文件夹npx husky install
- 在 package.json 中生成 prepare 指令( 需要 npm > 7.0 版本 )
npm set-script prepare "husky install"
- 执行 prepare 指令
npm run prepare
- 执行成功,提示
- 添加
commitlint
的hook
到husky
中,并指令在commit-msg
的hooks
下执行npx --no-install commitlint --edit "$1"
指令
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
执行命令后会在commit-msg文件中添加一行脚本:npx --no-install commitlint --edit $1
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# npx 是npm的一个免安装工具,
# 本质就是可以临时download执行某个二进制
# 如果想让 npx 强制使用本地模块,不下载远程模块,可以使用–no-install参数。如果本地不存在该模块,就会报错。
# 这个是采用线上的
# npx --no-install commitlint --edit $1
#这个是采用 依赖包里面的 node_modules
# ./wescrm/node_modules/.bin/commitlint --edit
# 使用yarn
yarn commitlint --edit $1
# # 提交记录检查
# yarn commitlint --edit $1
# # 格式化检查
# yarn format:check
# # eslint检查
# yarn lint:check
- 此时的
.husky
的文件结构
至此, 不符合规范的 commit 将不再可提交:
PS C:\Users\95645\Desktop\code\vue\wescrm> git commit -m "测试"
yarn run v1.22.18
warning ..\..\..\..\package.json: No license field
$ C:\Users\95645\Desktop\code\vue\wescrm\node_modules\.bin\commitlint --edit .git/COMMIT_EDITMSG
⧗ input: 测试
✖ 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
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
husky - commit-msg hook exited with code 1 (error)
如果执行报错:
可以将commit-config里面的
npx --no-install commitlint --edit $1
改为
yarn commitlint --edit $1
至此,就已经可以处理好了 强制规范化的提交要求,到现在 不符合规范的提交信息,将不可在被提交!
那么到这里我们的 规范化目标 就完成了吗?
当然没有!
现在我们还缺少一个 规范化的处理 ,那就是 代码格式提交规范处理!