大家好,我是尾号9527。爱技术,也爱生活。
在团队协作中,规范化 Git 提交信息不仅能提升代码的可维护性,还能帮助团队更好地管理版本历史。本文将介绍如何使用 husky、commitizen、commitlint 和 lint-staged 来规范 Git 提交。
安装并配置 husky
首先,我们需要安装 husky 来确保在 Git 提交前进行一些必要的钩子检查:
安装 husky
npm i husky -D
初始化 husky
通过下面的命令初始化 husky:
npx husky-init
这将在 package.json 的 scripts 属性中自动添加以下配置:
{
"scripts": {
"prepare": " husky install"
}
}
安装并配置 commitizen
commitizen 是一个工具,帮助开发者按照规范的格式提交 Git 信息,避免提交信息的格式不一致。
全局安装 commitizen
npm i commitizen -g
安装 cz-customizable
npm i cz-customizable -D
配置 commitizen
在 package.json 中添加以下配置,指向 cz-customizable:
"config": {
"commitizen": {
"path": "node_modules/cz-customizable"
}
}
创建并配置 .cz-config.js
在项目根目录下创建 .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)'
},
skipQuestions: ['body', 'footer'],
subjectLimit: 100
}
安装并配置 commitlint
为了确保 Git 提交符合规范,我们使用 Commitlint 来校验提交信息。
安装 commitlint
npm i @commitlint/cli @commitlint/config-conventional -D
配置 commitlint
在项目根目录下创建 commitlint.config.js 文件,添加以下内容:
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert', 'build'
]
],
'subject-case': [0] // 不做大小写校验
}
}
配置 husky 提交信息钩子
使用 husky 配置提交信息验证:
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
配置 lint-staged 进行代码检查
lint-staged 可以确保只有通过代码检查的文件才会提交,提升代码质量。
安装 lint-staged
npm i lint-staged -D
配置 lint-staged
在 package.json 中添加以下 lint-staged 配置:
"lint-staged": {
"*.{js,ts,vue}": ["eslint --fix", "prettier --write"],
"*.{css,scss}": ["stylelint"]
}
配置 pre-commit 钩子
编辑 .husky/pre-commit 文件,将默认的 npm test 改为执行 lint-staged:
npx lint-staged
配置 commit 脚本
在 package.json 中添加一个提交命令,简化提交流程:
{
"scripts": {
"commit": "git add . && git cz"
}
}
使用流程
每次提交时,执行以下命令来触发提交:
npm run commit
这样就会引导你通过命令行填写符合规范的提交信息,同时确保所有代码都经过 lint-staged 和 commitlint 校验。
总结
通过配置 husky、commitizen、Commitlint 和 lint-staged,你可以确保 Git 提交信息的一致性和代码质量。这些工具的结合不仅提高了团队的协作效率,也减少了因提交信息不规范而带来的麻烦。