前言
在项目开发过程中,我们经常会执行git commit命令来保存项目的修改。这些提交通常包含了提交信息,用于描述本次提交所做的修改。但是,如果提交信息不规范,会导致项目的版本历史难以阅读和理解,甚至会影响项目的开发进度;所以我们需要通过一些手段来规范我们的提交信息。
一、配置流程
- 先下载一波依赖
yarn add @commitlint/config-conventional @commitlint/cli husky lint-staged -D
// prettier和配置git提交验证无关,它是一个代码风格工具,这里使用它是为了帮我们理解lint-staged这个配置的作用
yarn add prettier -D
- 配置
prettier
- 2.1 根目录新建
.prettierrc.json配置代码风格
// 用于测试所以配置的比较简单
{
"printWidth": 160,
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
- 2.2 根目录新建
.prettierignore用于排除不需要格式化的目录或文件
dist
build
- 在
package.json中的scripts里新增一个脚本命令(这一点非常重要,他的作用就是在执行yarn installornpm install时会自动执行这个脚本;我之前就忘记加了导致别人在拉取项目后git提交验证就失效了,导致折腾大半天)
"prepare": "husky install"
- 执行命令
npx husky install
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'
npx husky add .husky/pre-commit 'npx lint-staged'
- 在根目录新建
commitlint.config.js,再贴上下面配置
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', // 新增功能
'del', // 删除功能
'fix', // 修复问题
'docs', // 文档变更
'style', // 代码风格/样式改动
'refactor', // 重构
'perf', // 性能优化
'test', // 增加测试
'chore', // 构建/辅助工具的变动
'revert', // 版本回退
'build', // 打包
],
],
},
}
- 在
package.json中新增下面两个配置
// husky是git钩子管理工具
"husky": {
// git commit 会执行pre-commit和commit-msg
"hooks": {
// 执行一些格式验证或者跑一些测试用例
"pre-commit": "lint-staged",
// 验证提交是否commitlint.config.js的规则
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
// lint-staged钩子工具:提交修改之前对提交信息进行检查或修复
"lint-staged": {
// 通过prettier对指定文件进行风格格式化后再提交
// 这一步需要下载依赖prettier
"*.{js,ts,tsx,json}": [
"prettier --write .",
"git add ."
]
}
git提交验证配置到这里就结束了!来看看效果图
7. 效果图
-
7.1 不规范提交
-
7.2 规范提交
下面是配置提交的便捷操作,有兴趣的可以继续配置。
二、便捷操作配置(不必要)
虽然说上面已经规范了提交验证,但是那么多提交类型很难记住,于是我们可以配置一个提交流程,我们只需要根据提示输入相应的内容就好了,它会自动生成提交记录,灰常的方便。
- 依旧是先安排一波依赖
yarn add commitizen@4.2.4 -g
yarn add cz-customizable@6.3.0 -D
- 在根目录新建
.cz-config.js文件
module.exports = {
// 提交类型
types: [
{ value: 'feat', name: 'feat: 新增功能' },
{ value: 'del', name: 'feat: 删除功能' },
{ value: 'fix', name: 'fix: 修复问题' },
{ value: 'docs', name: 'docs: 文档变更' },
{ value: 'style', name: 'style: 代码风格/样式改动' },
{ value: 'refactor', name: 'refactor: 重构' },
{ value: 'perf', name: 'perf: 性能优化' },
{ value: 'test', name: 'test: 增加测试' },
{ value: 'chore', name: 'chore: 构建/辅助工具的变动' },
{ value: 'revert', name: 'revert: 回退' },
{ value: 'build', name: 'build: 打包' },
], // 这个位置需要跟commitlint.config.js的配置配置对应
// 提交步骤
messages: {
type: '请选择提交类型(必填):',
customScope: '请输入修改范围(可选):',
subject: '请输入描述信息(必填):',
body: '请输入详细描述信息(可选):',
footer: '请输入要关闭的issue(可选):',
confirmCommit: '确认使用以上信息提交?(y/n)',
},
// 可选步骤
skipQuestions: ['scope', 'customScope', 'body','footer'],
// 描述信息长度
subjectLimit: 50,
}
- 在
package.json文件中新增一项配置
"config": {
"commitizen": {
"path": "node_modules/cz-customizable"
}
}
- 使用
git cz代替git commit - 效果图
写在最后
希望本篇文章能帮助你们遵循一些基本的提交规范,使你们可以更高效地使用git进行版本控制,让你们团队协作更加顺利。