安装 commitlint
- npm install --save-dev @commitlint/{cli,config-conventional}
配置 commitlint.config.js
项目根目录新增 commitlint.config.js 文件,写入以下默认配置
- module.exports = { extends: ['@commitlint/config-conventional'] };
或自定义配置
- module.exports = {
- extends: ['@commitlint/config-conventional'],
- rules: {
- 'type-enum': [2, 'always', [
- 'feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore', 'revert'
- ]],
- 'subject-full-stop': [0, 'never'],
- 'subject-case': [0, 'never']
- }
- }
安装 husky
- # 安装 Husky v6+ 版
- npm install husky --save-dev
- # or
- yarn add husky --dev
- # 激活 hooks
- npx husky install
- # or
- yarn husky install
- # 添加 hook
- npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'
- # or
- yarn husky add .husky/commit-msg 'yarn commitlint --edit $1'
测试
测试上一次提交的 commit
- npx commitlint --from HEAD~1 --to HEAD --verbose
测试当前提交的 commit
- git commit -m "foo: 这是错误的提交,因为foo不在允许的类型中"
提示以下错误
- ⧗ input: foo: 这是错误的提交,因为foo不在允许的类型中
- ✖ subject may not be empty [subject-empty]
- ✖ type may not be empty [type-empty]
- ✖ found 2 problems, 0 warnings
- ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
- husky - commit-msg hook exited with code 1 (error)
正确的提交 commit
- chore: 添加了 commitmsg 的校验功能
规范 commit
提交格式(注意冒号后面有空格)
- git commit -m <type>[optional scope]: <description>
type :用于表明我们这次提交的改动类型,是新增了功能?还是修改了测试代码?又或者是更新了文档?
optional scope:一个可选的修改范围。用于标识此次提交主要涉及到代码中哪个模块。
description:一句话描述此次提交的主要内容,做到言简意赅。
示例
- git commit -m "feat: 新增首页模块"
带修改范围的示例
- git commit -m 'fix(home): 修复页面样式问题'
修复样式问题,问题出在哪里?出在 home 的模块里面
常用的 type 类型
类型 | 描述 |
---|---|
build | 编译相关的修改,例如发布版本、对项目构建或者依赖的改动 |
chore | 其他修改, 比如改变构建流程、或者增加依赖库、工具等 |
ci | 持续集成修改 |
docs | 文档修改 |
feat | 新特性、新功能 |
fix | 修改bug |
perf | 优化相关,比如提升性能、体验 |
refactor | 代码重构 |
revert | 回滚到上一个版本 |
style | 代码格式修改, 注意不是 css 修改 |
test | 测试用例修改 |
类型的定义在 commitlint.config.js 中可根据实际修改
更多文档参考 https://commitlint.js.org/