Skip to content

在我们团队协作开发时,如果每个人的 git 的 commit 提交规范都不一样,最后的代码 review 或看 git 的 log 提交记录时就是一团乱,今天我们用 commit + husky 实现 git 提交规范化,保证错误的 commit 信息不能提交成功。

<!-- more -->

安装

安装 commitlint

shell
npm install --save-dev @commitlint/{cli,config-conventional}

生成配置文件

shell
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

commitlint 是检测我们提交的规范的,具体规范如下:

shell
<type>: <subject>

常见 type 类型

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

安装 husky

husky 能够实现 git hooks ,就是在我们使用 git 命令的时候,执行一些操作等,如这里就是在 git commit 时执行 commitlint 规范检测。

shell
npm install --save-dev husky

package.json 配置文件

json
// package.json
{
  "husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}

commitlint 配置文件

生成配置文件 commitlint.config.js,当然也可以是 .commitlintrc.js

shell
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

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

shell
"husky": {
    "hooks": {
      "commit-msg": "commitlint -e $HUSKY_GIT_PARAMS"
    }
  },

commitlint.config.js 文件配置

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

js
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],
  },
};

参考链接