Xu ShengXu Sheng

正确的工具、正确的方法、正确的方向,才能做正确的事情。

2020年4月10日工具534 words in 4 min


使用 commitizen 优化 git 提交

之前写了一篇博客,用来做备忘,每次有新项目的时候,就上去复制粘贴:

关于项目 git 协作流程的思考

但是因为有一些思考过程,所以不太方便施展 C+V 大法,现在汇总一下。

一、安装依赖

1
2
3
4
5
6
yarn add -D commitizen \
cz-conventional-changelog \
@commitlint/config-conventional \
@commitlint/cli \
husky \
standard-version

二、添加配置文件

在项目根目录下,添加 .commitlintrc.js 文件。

1
.commitlintrc.js

内容如下:

1
2
3
4
5
6
7
module.exports = {
extends: [
'@commitlint/config-conventional'
],
rules: {
}
};

三、修改 package.json 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 修改 scripts 部分
scripts: {
"commit": "git-cz",
"release": "standard-version"
}

// 修改或添加 config 字段
"config": {
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
}
}

// 修改或添加 kusky 字段
"husky": {
"hooks": {
"commit-msg": "commitlint -e $GIT_PARAMS"
}
},

四、总结

这个时候,运行 yarn commit 命令就可以提交代码.

1. 自动 release

运行 yarn release 命令就可以用来自动更新 package.json 中的 version 字段,生成或更新 CHANGELOG.md 文件,以及触发一次 release 提交并打上相应的 git tag

2. 修改 CHANGELOG.md 生成规则

如果想对生成的 CHANGELOG.md 自定义规则的话,可以参考:Conventional Changelog Configuration Spec (v2.1.0)

3. 第一次 release

第一次调用 yarn release 命令的话,加上 --first-release 参数,这样就不会自动修改当前 package.json 的版本号了。

4. 手动指定版本号

需要手动指定版本号的话,使用 --release-as <版本号> 参数。

5. 指定 git tag 的前缀

standard version 默认会在版本号之前加上 v 的前缀。

比如执行 standard version --release-as 1.1.0 命令,会发现分支被打上了 v1.1.0 标签。

如果想要指定前缀的话,可以使用 -t [前缀] 参数。

If you do not want to have any tag prefix you can use the -t flag without value.

官网上说的是如果不希望加前缀的话,-t 参数的值不给就行,但是我直接测试了一下,如果 -t 的值不给的话,还是加上的 v 前缀,必须得指定为空字符串 '' 才行。

如果对你有帮助,不如请我喝一杯星爸爸,或者留言鼓励下我哦 😘 ☕.