zl程序教程

您现在的位置是:首页 >  Java

当前栏目

前端代码风格自动化系列(二)之Commitlint

2023-02-18 16:40:28 时间

在有了Husky赋能之后,我们有能力在Git的钩子里做一些事情,首先不得不提的是代码的提交规范和规范的校验,优雅的提交,方便团队协作和快速定位问题。首推Commitlint,另外@加神 推荐了Gitmoji也是一个很有意思的工具。

安装

npm install --save-dev @commitlint/config-conventional @commitlint/cli

// 生成配置文件commitlint.config.js,当然也可以是 .commitlintrc.js
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

配置

在husky的配置加入CommitlIint配置,v1.0.1版本以后为HUSKY_GIT_PARAMSv0.14.3GIT_PARAMS

"husky": {
    "hooks": {
      "pre-commit": "npm run test",
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"
    }
  },

定制提交规范

提交格式(注意冒号后面有空格)

<type>: <subject>

常用的type类别

  • upd:更新某功能(不是 feat, 不是 fix)
  • feat:新功能(feature)
  • fix:修补bug
  • docs:文档(documentation)
  • style: 格式(不影响代码运行的变动)
  • refactor:重构(即不是新增功能,也不是修改bug的代码变动)
  • test:增加测试
  • chore:构建过程或辅助工具的变动

例子:

git commit -m 'feat: 增加 xxx 功能'
git commit -m 'bug: 修复 xxx 功能'

subject

subject是 commit 目的的简短描述,可以做一些配置,如最大长度限制。

commitlint.config.js文件配置

rule配置说明::rule由name和配置数组组成,如:'name:[0, 'always', 72]',数组中第一位为level,可选0,1,2,0为disable,1为warning,2为error,第二位为应用与否,可选always|never,第三位该rule的值。具体配置例子如下:

module.exports = {
  extends: [
    "@commitlint/config-conventional"
  ],
  rules: {
    'type-enum': [2, 'always', [
      'upd', 'feat', 'fix', 'refactor', 'docs', 'chore', 'style', 'revert'
     ]],
    'type-case': [0],
    'type-empty': [0],
    'scope-empty': [0],
    'scope-case': [0],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
    'header-max-length': [0, 'always', 72]
  }
};

这里列出了大部分常用的配置,其它的可以参考Commitlint网站,具体使用例子:

这里我们使用错误的提交方式,最上面的是自动测试的脚本,大家可以忽略,husky给出了commit-msg的input为xxx,触发了subject-emptytype-empty两个规则,提交不符合规范,被拦了下来。如果是正确的提交,例子如下:

关于Commitlint的使用就到这里了。