Git 提交规范:如何通过 Commitlint + Husky 实现团队代码提交标准化

115 阅读3分钟

一、前言

在多人协作的前端项目中,Git 提交信息混乱 是一个常见问题:

  • git commit -m "fix"
  • git commit -m "更新代码"
  • git commit -m "test123"

这类模糊的提交信息不仅难以追溯问题,还影响 自动化生成 changelog语义化版本发布Code Review 效率

本文将带你使用 Commitlint + Husky,实现 Git 提交信息的自动化校验与标准化,提升团队协作规范性。


二、为什么要规范 Git 提交?

✅ 好处:

  • 清晰的版本历史:一眼看出每次提交的目的。
  • 自动生成 changelog:如 conventional-changelog
  • 支持语义化版本(SemVer)自动升级fixpatchfeatminor
  • 提升 Code Review 效率:通过提交类型快速分类。

三、常用的 Git 提交规范

1. Angular 规范(最流行)

格式:<type>(<scope>): <subject>

feat(user): add login validation
fix(api): handle timeout error
docs(readme): update installation guide
style(css): format button styles
refactor(util): simplify helper functions
test(login): add unit test for form
chore(deps): upgrade webpack to v5

2. 常见 type 类型说明

type说明
feat新功能
fix修复 bug
docs文档更新
style代码格式调整(不影响逻辑)
refactor代码重构
test测试相关
chore构建过程或辅助工具变动
perf性能优化
ciCI/CD 配置修改

四、实现方案:Commitlint + Husky

我们使用:

  • Commitlint:校验提交信息是否符合规范。
  • Husky:Git 钩子工具,在 git commit 时触发校验。

五、实战步骤

1. 初始化项目(如未使用)

npm init -y
git init

2. 安装依赖

npm install --save-dev @commitlint/config-conventional @commitlint/cli husky

3. 创建 Commitlint 配置文件

echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js

或使用 commitlint.config.json

{
  "extends": ["@commitlint/config-conventional"]
}

4. 配置 Husky

# 初始化 Husky
npx husky install

# 创建 commit-msg 钩子
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'

commit-msg 钩子会在每次提交时运行,校验提交信息。


5. 测试提交

git add .
git commit -m "hello"  # ❌ 不符合规范,提交失败

错误提示

❌   type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]
git commit -m "feat: add user profile page"  # ✅ 符合规范,提交成功

六、进阶配置(可选)

1. 自定义提交规则

修改 commitlint.config.js

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [2'always', [
      'feat''fix''docs''style''refactor''test''chore''perf'
    ]],
    'subject-min-length': [2'always'10], // 主题最少10个字符
    'header-max-length': [2'always'72]   // 标题最多72字符
  }
};

2. 集成 Commitizen(可选)

让团队成员通过命令行向导生成规范提交:

npm install --save-dev commitizen cz-conventional-changelog
echo '{ "path": "cz-conventional-changelog" }' > .czrc

使用:

npx cz
# 按提示选择 type、scope、subject

七、与 CI/CD 集成

在 GitHub Actions、GitLab CI 等流程中添加校验步骤:

# .github/workflows/lint.yml
name: Lint
on: [push]
jobs:
  commit-lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - run: npx commitlint --from=HEAD~1

✅ 防止不规范提交进入主分支。


八、团队落地建议

建议说明
统一规范团队内部约定 type、scope 使用规则
文档化CONTRIBUTING.md 中说明提交规范
培训引导新成员入职时进行培训
配合工具推荐使用 cz 或 IDE 插件辅助输入
持续执行在 CI 中强制校验,避免绕过

九、总结

通过 Commitlint + Husky,我们可以:

  • ✅ 强制团队遵守 Git 提交规范。
  • ✅ 提升代码历史可读性。
  • ✅ 为自动化发布(如 semantic-release)打下基础。
  • ✅ 减少无效的提交信息。

这不仅是代码规范的体现,更是 团队工程化成熟度 的标志。