规范的 commit message 能让项目历史清晰可读,便于自动化工具处理(如生成 CHANGELOG、语义化版本号)。
Git Commit 规范
Conventional Commits
Conventional Commits 是目前最广泛采用的 commit 规范,也是 Angular 团队提出并推广的标准。
基本格式
1 2 3 4 5
| <type>[optional scope]: <description>
[optional body]
[optional footer(s)]
|
- type: 必填,提交类型
- scope: 可选,影响范围
- description: 必填,简短描述(英文项目用小写开头,不加句号)
- body: 可选,详细说明
- footer: 可选,关联 issue、breaking change 等
常用 type
| type |
说明 |
feat |
新功能 |
fix |
修复 bug |
docs |
文档更新 |
style |
代码格式(不影响逻辑) |
refactor |
重构(不新增功能,不修 bug) |
perf |
性能优化 |
test |
测试相关 |
chore |
构建、依赖、工具等杂项 |
ci |
CI/CD 配置 |
build |
构建系统或外部依赖变更 |
revert |
回滚之前的提交 |
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| feat: add search feature fix: resolve login redirect loop docs: update API documentation chore: upgrade hexo to 8.1.1
feat(auth): add OAuth2 login support fix(blog): correct post date formatting refactor(css): extract common variables
feat: add RSS feed generation
Implemented Atom and RSS 2.0 feed generation. Feed path configurable via _config.yml.
Closes
feat!: remove legacy API v1 endpoints
BREAKING CHANGE: API v1 endpoints are no longer supported. Clients must migrate to v2.
|
感叹号标记 Breaking Change
在 type/scope 后加 ! 表示不兼容变更:
1 2
| feat!: drop Node.js 12 support refactor(db)!: change schema for user table
|
等效于在 footer 中写 BREAKING CHANGE:。
为什么需要规范
- 可读性:一目了然知道每个提交做了什么
- 自动生成 CHANGELOG:工具可解析提交历史,自动生成发布说明
- 语义化版本:根据
feat / fix / BREAKING CHANGE 自动决定版本号
- CI 自动化:触发不同的构建、测试、部署流程
相关工具
commitlint 配置示例
1
| npm install --save-dev @commitlint/cli @commitlint/config-conventional
|
1 2 3 4
| export default { extends: ['@commitlint/config-conventional'] };
|
1 2
| npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'
|
注意事项
- 一个提交只做一件事:避免把不相关的改动混在一个 commit 里
- 描述用祈使句:如
add feature 而非 added feature 或 adds feature
- 描述不超过 72 个字符:确保在终端中完整显示
- 用 body 解释 why:描述做了什么不是重点,代码已经说了;解释为什么这样做才更有价值