git提交规范
Angular团队规范延伸出的Conventional Commits specification(约定式提交)
使用Commitizen规范化提交代码
当你使用commitizen进行代码提交时(git commit)时,commitizen会提交你在提交时填写所有必需的提交字段
全局安装Commitizen:
1 | npm install -g commitizen |
项目内安装cz-customizable:
1 | npm install cz-customizable@6.3.0 --save-dev |
在package.json中配置commitizen:
... "config": { "commitizen": { "path": "node_modules/cz-customizable" } }
项目根目录下创建 .cz-config.js
自定义提示文件
module.exports = { // 可选类型 types: [ { value: 'feat', name: 'feat: 新功能' }, { value: 'fix', name: 'fix: 修复' }, { value: 'docs', name: 'docs: 文档变更' }, { value: 'style', name: 'style: 代码格式(不影响代码运行的变动)' }, { value: 'refactor', name: 'refactor: 重构(既不是增加feature,也不是修复bug)' }, { value: 'perf', name: 'perf: 性能优化' }, { value: 'test', name: 'test: 增加测试' }, { value: 'chore', name: 'chore: 构建过程或辅助工具的变动' }, { value: 'revert', name: 'revert: 回退' }, { value: 'build', name: 'build: 打包' } ], // 消息步骤 messages: { type: '请选择提交类型:', customScope: '请输入修改范围(可选):', subject: '请简要描述提交(必填):', body: '请输入详细描述(可选):', footer: '请输入要关闭的issue(可选):', confirmCommit: '确认使用以上信息提交?(y/n/e/h)' }, // 跳过问题 skipQuestions: ['body', 'footer'], // subject文字长度默认是72 subjectLimit: 72 }
最后,我们使用`git cz`代替`git commit`实现规范化的提交,但依旧存在有人可能会忘记使用的问题,因此我们得对该问题进行解决:
挡我们的‘commit’信息不符合约定式提交规范的时候,阻止当前的提交,并抛出对应的错误提示,因此我们得明白git的生命周期,在正确的时间做正确的事,git hooks有许多生命周期函数,这里我们只需要用到两个:
1 2 | commit-msg //用来规范化标准格式,并且可以按需指定是否要拒绝本次提交 pre-commit //会在提交前被调用,并且可以按需指定是否要拒绝本次提交 |
使用husky + commitlint检查提交描述是否符合规范要求:
-
commitlint:用于检查提交信息
-
husky:是
git hooks
工具
安装commitlint:
1 | npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4 |
创建 commitlint.config.js
文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | module.exports = { // 继承的规则 extends : [ '@commitlint/config-conventional' ], // 定义规则类型 rules: { // type 类型定义,表示 git 提交的 type 必须在以下类型范围内 'type-enum' : [ 2, // 当前验证的错误级别 'always' , // 在什么情况下进行验证 [ 'feat' , // 新功能 feature 'fix' , // 修复 bug 'docs' , // 文档注释 'style' , // 代码格式(不影响代码运行的变动) 'refactor' , // 重构(既不增加新功能,也不是修复bug) 'perf' , // 性能优化 'test' , // 增加测试 'chore' , // 构建过程或辅助工具的变动 'revert' , // 回退 'build' // 打包 ] ], // subject 大小写是否做校验 'subject-case' : [0] } }<br> // 注意:保存时一定要是UTF-8 |
安装husky:
1 | npm install husky@7.0.1 --save-dev |
启动hooks,生成.husky文件夹:
1 | npx husky install |
在 package.json
中生成 prepare
指令( 需要 npm > 7.0 版本 ):
1 | npm set-script prepare "husky install" |
执行 prepare
指令:
1 | npm run prepare |
添加 commitlint
的 hook
到 husky
中,并指令在 commit-msg
的 hooks
下执行 npx --no-install commitlint --edit "$1"
指令:
1 | npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"' |
至此, 不符合规范的 commit 将不再可提交
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义