Git 提交规范

1,774 阅读2分钟

husky

用来lint 提交消息运行测试lint 代码等。Husky 支持所有Git 钩子。

yarn add husky --dev
yarn add pinst --dev # ONLY if your package is not private
yarn husky install
husky add .husky/pre-commit "npm test" // v6

husky官方文档地址 typicode.github.io/husky/#/?id…

lint-staged

在代码提交之前,进行代码规则检查能够确保进入git库的代码都是符合代码规则的。但是整个项目上运行lint速度会很慢,lint-staged能够让lint只检测暂存区的文件,所以速度很快。

yarn add lint-staged --dev
husky add .husky/pre-commit "yarn lint-staged"

package.json

"husky": { // v4
    "hooks": {
      "pre-commit": "lint-staged"
    }
 },
"lint-staged": {
    "*.{js,ts,vue}": "eslint --fix",
    "*.{scss,css}": "prettier --write"
 }

Git commit 规范

<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>

type

用于说明 commit 的类别,只允许使用下面7个标识。

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

scope

scope用于说明 commit 影响的范围,比如数据层、控制层、视图层等等,视项目不同而不同。

subject

subject是 commit 目的的简短描述,不超过50个字符。

body

Body 部分是对本次 commit 的详细描述,可以分成多行。

footer

Footer 部分只用于以下两种情况:

  • 不兼容变动
  • 关闭 issue
  • revert 如果当前 commit 用于撤销以前的 commit,则必须以revert:开头,后面跟着被撤销 Commit 的 Header。

校验commit是否符合规则

安装

yarn add @commitlint/cli @commitlint/config-conventional --dev

配置

commitlint.config.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],
  },
};
# .husky/commit-msg (v7)
# ...
npx --no-install commitlint --edit $1
# or
yarn commitlint --edit $1

自动生成满足规则的commit信息

安装

yarn add commitizen cz-conventional-changelog --dev

配置

package.json

"config": {
   "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
   }
}

使用 git cz 代替 git commit 来生成 commit信息 参考

juejin.cn/post/688607…

www.jianshu.com/p/201bd81e7…