标准化 commit 及版本管理

397 阅读2分钟

起因

我们期望在 Git 提交时能够规范 commit 信息;发布版本时,将 commit 信息与版本有更加可靠的管理。就好像映射列表一样,清晰的知道每次更新了什么;并且能自动的去更新这个列表。

commitLint + husky

  • commitLint: 检查 commit 提交信息
# 安装
$ npm install --save-dev @commitlint/{cli,config-conventional}

# 使用conventional规范
$ echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
  • husky(V7):hook 工具,作用于git-commitgit-push阶段
npx husky-init && npm install       # 使用 npm 初始化 husky
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'  # commit-msg hook
npx husky add .husky/pre-commit "npm test"   # pre-commit hook

如果使用了规范友好的 commit 规则,可以在项目中添加一个 commitizen tag

https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b2fb174032f44be8b9e549ae3beea9a7~tplv-k3u1fbpfcp-zoom-1.image

[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)

standard-version

一个用于生成CHANGELOG.md和进行SemVer(语义化版本号)发版的命令行工具

主要功能

  • 自动修改最新版本号,可以是package.json或者自定义一个文件
  • 读取最新版本号,创建一个最新的git tag
  • 根据提交信息,生成CHANGELOG.md
  • 创建一个新提交包括  CHANGELOG.mdpackage.json

standard-version  会根据提交的信息类型来自动更改对应的版本号,如下:

  • feat: 次版本(minor)+1
  • fix: 修订号(patch) +1
  • BREAK CHANGE: 主板号(marjor) +1

standard-verstion  生成的CHANGELOG只会包含feat,fix,BREACK-CHANGE类型的提交记录

添加脚本

{
 scripts:{
   "release": "standard-version",
   "release:alpha": "standard-version --prerelease alpha",
   "release:rc": "standard-version --prerelease rc"
  }
}

standard-version本身只针对本地,并没有push才操作,我们可以在最后一步生成 tag 后,执行 push 操作,在paceage.json中添加 scale

"standard-version": {
    "scripts": {
      "posttag": "git push --follow-tags origin master && npm publish"
    }
  }

FAQ

🐞  husky 没有触发 pre-commit ?

✅  版本问题,v3/v4 可以直接在 package.json 中通过 hooks 配置,触发 pre-commit;但是 v5 之后需要通过 husky add xxx 来添加 hook

# before
"husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },

Links

Husky - Git hooks

JELLY DESIGN | 京东零售官方设计共享平台