使用husky7.0来规范Git提交

前端小贺 -
使用husky7.0来规范Git提交
大家好,我是前端小贺,希望能够通过自己的学习输出给你带来帮助。背景

在一个完整的工作流中,Git提交规范是一定需要的。Git提交规范包括什么呢?

我觉得应该包括代码的质检以及commit message校验。

我们使用husky来添加我们上述的需求:

husky是利用Git hooks(下面有常见的Git hooks)在git的钩子函数中(比如pre-commitcommit-msg)做一些事情。下面是官方的介绍:

Modern native Git hooks made easy

声明:我们使用的husky的版本是7.0及之后的版本

安装husky

好了,打开项目的根目录,执行`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-msg hook

接下来,我们限制下commit messge规范。

我们需要采用npm社区中比较成熟的两个依赖包@commitlint/cli,@commitlint/config-conventional

@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 hookspre-commitgit 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 checkoutgit switch执行后如果不使用--no-checkout参数,则在git clone之后也会执行。post-mergegit commit执行后在执行git pull时也会被调用pre-pushgit push执行前 最后

您的每一个点赞及评论都是对我坚持写作最大的支持!
另外希望各位朋友和我交流讨论,如有不对的地方,更希望批评指正!

我是前端小贺,希望能够通过自己的学习输出给你带来帮助。
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

gitjavascripthusky

扩展阅读

加个好友,技术交流

1628738909466805.jpg