使用husky7.0来规范Git提交
前端小贺 -大家好,我是前端小贺,希望能够通过自己的学习输出给你带来帮助。背景
在一个完整的工作流中,Git提交规范是一定需要的。Git提交规范包括什么呢?
我觉得应该包括代码的质检以及commit message校验。
我们使用husky来添加我们上述的需求:
husky是利用Git hooks
(下面有常见的Git hooks
)在git
的钩子函数中(比如pre-commit
、commit-msg
)做一些事情。下面是官方的介绍:
声明:我们使用的husky的版本是7.0
及之后的版本
好了,打开项目的根目录,执行`npm install husky --save-dev
,前提是生成了package.json
npm install husky --save-dev
我们按照官方的文档,进行husky install
:
注意点:这里的npm
的版本必须为7.1
及之后的版本(https://github.com/npm/cli/re...)
npm set-script prepare "husky install"
npm run prepare
添加eslint hook我们来配置eslint
校验
npx husky add .husky/pre-commit "npm run lint"
git add .husky/pre-commit
上述我们为什么能够配置npm run lint
呢,是因为我们的package.json
文件中的script
中包含了lint
:
{
"scripts": {
"lint": "vue-cli-service lint"
}
}
ok,至此我们在commit
的时候就会校验代码了,我们试一下:
git commit -m"验证"
> [email protected] lint
> vue-cli-service lint
DONE No lint errors found!
如上,我们提交的时候执行了lint
脚本。
接下来,我们限制下commit messge规范。
我们需要采用npm社区中比较成熟的两个依赖包@commitlint/cli
,@commitlint/config-conventional
。
commit message
规范接下来我们安装下两个包,并添加相关的配置文件:
npm install @commitlint/cli @commitlint/config-conventional --save-dev
echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > commitlint.config.js
ok,至此我们可以校验commit meassage
中的内容了,我们测试一下:
git commit -m"1"
> [email protected] lint
> vue-cli-service lint --mode production
The following files have been auto-fixed:
src/utils/secret.js
DONE All lint errors auto-fixed.
npm ERR! canceled
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/hsm/.npm/_logs/2022-04-26T02_21_07_564Z-debug.log
husky - commit-msg hook exited with code 1 (error)
如上,我们 commit message
随便写了点东西,就校验住了。我们修改下我们的commit message
重新commit
下:
git commit -m"docs: 添加husky相关"
> [email protected] lint
> vue-cli-service lint --mode production
DONE No lint errors found!
[committest b61be77] docs: 添加husky相关
1 file changed, 2 insertions(+)
Ok,成功了~
提交规范关于git commit message
提交规范,我们可以参考阮一峰的Commit message 和 Change log 编写指南。
在VSCode
中,我们采用了Conventional Commits
插件来进行commit提交
git commit
执行前可以通过git commit --no-verify
绕过commit-msggit commit
执行前可以用git commit --no-verify
绕过post-commitgit commit
执行后不影响git commit
的结果pre-merge-commitgit merge
执行前可以用git merge --no-verify
绕过。prepare-commit-msggit commit
执行后,编辑器打开之前 pre-rebasegit rebase
执行前 post-checkoutgit checkout
或git switch
执行后如果不使用--no-checkout
参数,则在git clone
之后也会执行。post-mergegit commit
执行后在执行git pull
时也会被调用pre-pushgit push
执行前 最后您的每一个点赞及评论都是对我坚持写作最大的支持!
另外希望各位朋友和我交流讨论,如有不对的地方,更希望批评指正!