大家好,我是前端小贺,希望能够通过自己的学习输出给你带来帮助。
背景
在一个完整的工作流中,Git提交规范是一定需要的。Git提交规范包括什么呢?
我觉得应该包括代码的质检以及commit message校验。
我们使用husky来添加我们上述的需求:
husky是利用Git hooks(下面有常见的Git hooks)在git的钩子函数中(比如pre-commit、commit-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"验证"
> webpack-vue@2.1.0 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.jsok,至此我们可以校验commit meassage中的内容了,我们测试一下:
git commit -m"1"
> webpack-vue@2.1.0 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相关"
> webpack-vue@2.1.0 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 hooks
| pre-commit | git commit执行前 | 可以通过 git commit --no-verify绕过 | 
|---|---|---|
| commit-msg | git commit执行前 | 可以用 git commit --no-verify绕过 | 
| post-commit | git commit执行后 | 不影响 git commit的结果 | 
| pre-merge-commit | git merge执行前 | 可以用 git merge --no-verify绕过。 | 
| prepare-commit-msg | git commit执行后,编辑器打开之前 | |
| pre-rebase | git rebase执行前 | |
| post-checkout | git checkout或git switch执行后 | 如果不使用 --no-checkout参数,则在git clone之后也会执行。 | 
| post-merge | git commit执行后 | 在执行 git pull时也会被调用 | 
| pre-push | git push执行前 | 
最后
您的每一个点赞及评论都是对我坚持写作最大的支持!
另外希望各位朋友和我交流讨论,如有不对的地方,更希望批评指正!
我是前端小贺,希望能够通过自己的学习输出给你带来帮助。
 
                             
                         
                            