企业级 Git 提交规范配置指南 (From 0 to 1)
本文档将指导你如何在项目中集成 Husky + Commitlint + Commitizen,实现自动化的代码与提交信息规范检查。
1. 核心工具安装 (Commitlint)
首先安装 Commitlint 及其标准配置。这是“裁判”,负责判断提交信息是否合格。
1.1 安装依赖
在项目根目录下执行:
npm install -D @commitlint/cli @commitlint/config-conventional
1.2 创建配置文件
在根目录新建文件 commitlint.config.js,内容如下:
module.exports = {
extends: ['@commitlint/config-conventional'],
// 你可以在这里自定义规则,例如:
// rules: {
// 'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert']],
// }
};
2. 自动化钩子配置 (Husky)
Husky 是“触发器”,它利用 Git Hooks 在你敲击回车提交时拦截操作。
2.1 安装并初始化 Husky
注意:Husky v9 的初始化命令非常简化。
npm install -D husky
npx husky init
执行完 npx husky init 后,你的 package.json 会自动增加 "prepare": "husky" 脚本,并且根目录下会生成 .husky 文件夹。
⚠️ 常见报错预警:
init命令会自动创建一个.husky/pre-commit文件,内容默认是npm test。 如果你的package.json中没有定义test脚本,提交时就会报错Missing script: "test"。 解决方法:打开.husky/pre-commit文件,删除里面的npm test,暂时留空即可(后续在第 6 步我们会配置它)。
2.2 添加 commit-msg 钩子
我们需要告诉 Husky:在提交信息生成之前,请用 Commitlint 检查一下。
在终端执行(Mac/Linux):
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
Windows 用户 (PowerShell) 请执行:
Set-Content .husky/commit-msg 'npx --no -- commitlint --edit $1'
或者手动在 .husky 文件夹下新建文件 commit-msg (无后缀),内容写入:
npx --no -- commitlint --edit $1
3. 交互式提交助手 (Commitizen & cz-git) - 可选但推荐
为了不用每次都手敲 feat: ...,我们可以安装一个工具,通过选择的方式生成提交信息。这里推荐使用 cz-git,它比老牌的 cz-conventional-changelog 更轻量、更漂亮。
3.1 安装依赖
npm install -D commitizen cz-git
3.2 修改 package.json
打开 package.json,在顶级层级(与 scripts 同级)添加 config 字段:
{
"scripts": {
"commit": "git-cz"
},
"config": {
"commitizen": {
"path": "node_modules/cz-git"
}
}
}
3.3 测试交互式提交
以后你可以使用 npm run commit 来代替 git commit。
4. 验证是否成功
测试 1:错误的提交
尝试在终端输入一个不规范的提交:
git add .
git commit -m "随便写点什么"
预期结果: 终端报错,提示 subject may not be empty 或 type must be one of [feat, fix...],提交失败。这说明 Husky 拦截成功了。
测试 2:正确的提交
git commit -m "chore: 初始化 git 规范配置"
预期结果: 提交成功。
5. 附录:提交类型速查表 (Conventional Commits)
团队成员在提交时应遵循以下前缀:
| 类型 (Type) | 含义 | 示例 |
|---|---|---|
| feat | 新增功能 (Feature) | feat: 增加用户登录功能 |
| fix | 修复 Bug | fix: 修复上传文件时的跨域问题 |
| docs | 文档变更 | docs: 更新 README.md |
| style | 代码格式 (不影响逻辑,如空格、分号) | style: 删除多余空行 |
| refactor | 代码重构 (不修 Bug 也不加功能) | refactor: 优化大文件切片逻辑 |
| perf | 性能优化 | perf: 优化 ECharts 渲染速度 |
| test | 测试相关 | test: 增加单元测试 |
| chore | 构建/工具/依赖变动 | chore: 升级 express 版本 |
| revert | 回滚代码 | revert: 回滚上一次提交 |
6. 进阶:代码质量检查 (Lint-staged)
如果你希望在提交时,不仅检查提交信息,还要自动扫描代码(ESLint/Prettier)是否有错误,请继续配置 lint-staged。
6.1 安装
npm install -D lint-staged
6.2 配置 package.json
在 package.json 中添加:
{
"lint-staged": {
"*.{js,vue,ts}": [
"eslint --fix",
"prettier --write"
]
}
}
(前提是你项目中已经配置了 eslint 和 prettier)
6.3 修改 Husky 的 pre-commit 钩子
找到 .husky/pre-commit 文件,将其内容修改为:
npx lint-staged
现在,你的流程变成了:
git commit- Husky 触发
pre-commit-> 运行 Lint-staged (检查代码格式,有问题直接报错或自动修复)。 - Husky 触发
commit-msg-> 运行 Commitlint (检查提交文字,格式不对报错)。 - 一切通过 -> 真正生成 Commit。