步骤 1: 安装 Commitizen
Commitizen 是一个帮助你编写合规的 Git 提交信息的工具。
首先全局安装 commitizen
npm install -g commitizen
步骤 2: 初始化项目
局部:
在你的项目目录下,初始化 Commitizen,会在package.json 生成个config commitizen配置:
commitizen init cz-conventional-changelog --save-dev --save-exact
全局
npm install -g cz-conventional-changelog
配置 .czrc文件:
在Windows上,你还是需要一个 .czrc
文件来告诉 commitizen
使用 cz-conventional-changelog
适配器。你可以在命令行使用 echo
和重定向来创建此文件,或者使用文本编辑器手动创建。
在命令行中,你可以这样做:
echo { "path": "cz-conventional-changelog" } > %USERPROFILE%\.czrc
或者你可以手动创建一个 .czrc
文件在你的用户目录(通常是 C:\Users\你的用户名
),然后输入:
{ "path": "cz-conventional-changelog" }
步骤 3. 使用 Commitizen:
现在你应该可以在你的 git 仓库中使用 git cz
来运行 commitizen
,并且 commitizen
会使用 cz-conventional-changelog
适配器来帮助你创建提交信息。
自定义提交git规范配置详细
1.安装npm i cz-customizable --save-dev
2.配置package.json:
"config": { "commitizen": { "path":"node_modules/cz-customizable" } }
3.根目录下创建 .cz-config.js
文件:
module.exports = {
// 可选类型
types:[
{ value: 'feat', name: 'feat: 新功能'},
{ value: 'fix', name: 'fix: 修复'},
{ value: 'delete', name: 'delete: 删除'},
],
// 步骤
messages: {
type: '提交的类型',
customScope: '修改的范围(可选)',
subject: '请简要描述提交(必填)',
body: '详细描述(可选)',
footer: '请选择要关闭的issue(可选)',
confirmCommit: '确认要使用以上信息提交?(y/n)'
},
// 跳过步骤
skip: ['body', 'footer'],
// 默认长度
subjectLimit: 72
}
4.执行 git cz
的时候即可按照自己配置的规范
husky + commitlint
检查提交
不使用git cz
, 直接使用了 git commit -m "my commit"
, 依然会提交上去,项目中会出现不规范的提交。
husky + commit-msg + commitlint 校验我们的提交信息是否符合提交规则。
1.安装 npm install --save-dev @commitlint/config-conventional @commitlint/cli
2.配置commitlint.config.js文件 :
module.exports = {
extends: ['@commitlint/config-conventional'],
// 定义规则类型
rules: {
// type 类型定义,表示 git 提交的 type 必须在以下类型范围内
'type-enum': [
2,
'always',
[
'feat', // 新功能
'fix', // 修复
'delete', // 删除
]
],
// subject 大小写不做校验
'subject-case': [0]
}
}
3.安装 npm install husky --save-dev
4.输入npx husky install,
生成 .husky 文件夹 。
5. package.json 中配置:
"scripts": {
"prepare":"husky install"
},
6.执行 npm run prepare
7.commitlint 的 hook 到 husky 中,commit-msg
时进行校验:
*.你需要在 husky
的配置中添加 commit-msg
钩子以使用 commitlint
。
如果你正在使用 husky
v7,你应该在项目的 .husky
目录下创建一个 commit-msg
文件,文件内容如下:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1
*.如果你是在 package.json
文件中配置 husky
,你可以添加 commit-msg
钩子,如下所示:
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
8.恭喜你完成。