好的提交信息
约 632 字大约 2 分钟
2025-11-09
什么样的提交信息是“好的提交信息”?
一个好的 commit message 应该能做到:
- 一眼就能看出改动的 目的;
- 自动生成 CHANGELOG、版本号;
- 便于 回溯问题、快速阅读项目历史。
因此,业界最常用的规范是:
Conventional Commits 规范
格式如下:
<type>(<scope>): <subject>例如:
feat(router): 支持动态参数匹配
fix(auth): 修复 token 过期后无法刷新问题
refactor(core): 优化依赖注入逻辑
docs(readme): 补充安装说明
style: 调整 eslint 规则
test(utils): 增加日期格式化单元测试
chore(ci): 更新 GitHub Actions 配置type 常用类型一览
| 类型 | 说明 |
|---|---|
feat | 新功能 |
fix | 修复 bug |
refactor | 重构代码(不影响功能) |
perf | 性能优化 |
style | 代码格式调整(空格、缩进、分号) |
test | 添加或修改测试 |
docs | 文档变更 |
build | 构建系统或依赖相关变更 |
chore | 其他杂项任务 |
ci | CI/CD 配置相关 |
revert | 回滚提交 |
提示:
scope 是可选的,比如 feat(router): ...。
如果项目模块多,用 scope 标记更清晰。
好 vs 坏 示例对比
| 不规范提交 | 改进后提交 |
|---|---|
| “修改 bug” | fix(user): 修复登录后用户信息不更新问题 |
| “优化代码” | refactor(core): 简化响应式依赖收集逻辑 |
| “更新文档” | docs(readme): 补充 API 参数说明 |
| “新增功能” | feat(todo): 支持任务完成状态切换 |
用 Husky + Commitlint 强制执行规范
这套组合让你:
- 自动校验 commit message 格式
- 不符合规范的提交会被直接阻止
安装依赖
npm install --save-dev husky @commitlint/{cli,config-conventional}新建配置文件
在项目根目录新建文件: commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
}这会继承上面提到的 Conventional Commits 标准。
添加 Husky 钩子
先启用 Husky(如果你之前没加过):
npx husky install
npm pkg set scripts.prepare="husky install"再添加 commit-msg 钩子:
npx husky add .husky/commit-msg 'npx commitlint --edit "$1"'生成的 .husky/commit-msg 文件内容类似:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx commitlint --edit "$1"测试一下
git commit -m "update something"会被拒绝提交:
⧗ input: update something
✖ subject may not be empty [subject-empty]
✖ type may not be empty [type-empty]
✖ found 2 problems, 0 warnings改成:
git commit -m "feat(core): 添加自动路由注册机制"最佳实践
git commit -m "feat(core): 支持动态模块加载"
│
▼
Husky 触发 commitlint → 校验格式
│
▼
git push 触发 CI/CD
│
▼
npm run release → 自动生成 CHANGELOG.md + 版本号升级 + 提交 Tag
│
▼
(可选) semantic-release 自动发布到 npm/github