在一个开发团队中,前端开发的代码管理越来越规范化、工程化,而代码commit更是需要一个统一的规范去约束,保证代码commit时的规范性。尤其多人参与一个项目开发时,大家的代码commit风格不相同,不便于后续的代码统一管理和可读性;所以良好的git commit风格是很重要的。
很多时候我们提交代码时,运行
git commmit -m 'xxx'
即可,而commitlint可以对message进行约束,是判断message是否符合格式要求的工具。commitlint 推荐结合config-conventional 配置使用,正确的提交格式是:git commit -m[optional scope]:
type :说明代码提交的类型。
optional scope:一个可选的修改范围。
description:描述提交的主要内容。
常见的type类型
fix:Bug 修复
docs:文档更新
style:代码样式更改,例如空格、格式、缺少分号等
refactor:重构代码
perf:性能优化
test:添加缺失或修正测试代码
chore:构建相关的代码或工具库,如文档生成等
commitlint仅仅规范git commit -m
[optional scope]: 这样的格式去提交代码,每次提交时都需要输入type,这样比较麻烦,所以需要使用commitizen辅助工具来自动生成提交信息。
commitizen是规范commit message的工具,提供选择的commit message类型,快速生成commit message说明;而cz-customizable作为它的适配器,可以定制提交说明信息的type。
进行代码质量规范检查时,husky可以阻止不符合规范的commit,push等操作,husky是注册在git pre-commit钩子函数被调用时执行lint-staged,pre-commit
钩子在git commit
时就会触发。lint-staged对暂存区中有改动的文件根据ESLint 和 Prettier的规则进行检测;eslint+husky+prettier+lint-staged工具的配合使用可以规范我们的代码格式统一,进行代码格式检查 和代码美化,保证代码质量。
安装
npm install @commitlint/cli @commitlint/config-conventional -D
在根目录下新建.commitlintrc.js或者commitlint.config.js文件
module.exports = {
extends: ['@commitlint/config-conventional']
};
安装
npm install commitizen cz-customizable -D
在根目录下新建.cz-config.js文件,配置commit type。
// 提交代码:使用 npx cz 命令
// 相关配置:https://github.com/leoforfree/cz-customizable
module.exports = {
types: [
{
value: 'feat',
name: '✨ feat(新功能)'
},
{
value: 'fix',
name: ' fix(Bug 修复)'
},
{
value: 'docs',
name: ' docs(文档更新)'
},
{
value: 'style',
name: ' style(代码样式更改,例如空格、格式、缺少分号等)'
},
{
value: 'refactor',
name: ' refactor(重构代码)'
},
{
value: 'perf',
name: '⚡️ perf(性能优化)'
},
{
value: 'test',
name: '✅ test(添加缺失或修正测试代码)'
},
{
value: 'chore',
name: ' chore(构建相关的代码或工具库,如文档生成等)'
}
],
messages: {
type: '请选择提交类型:(必填)',
customScope: '请输入影响范围:(可选)',
subject: '请输入简要描述:(必填)',
body: '请输入详细描述,使用 "|" 分行:(可选)',
breaking: '请列出所有的破坏性变更,例如:描述、理由或迁移方式等:(可选)',
footer: '请列出需关闭的 issue,例如:#31, #34:(可选)',
confirmCommit: '请确认此提交信息?'
},
subjectLimit: 100,// subject文字长度默认
allowCustomScopes: true,
allowBreakingChanges: ['feat', 'fix'],
skipQuestions: ['scope', 'footer'] //默认跳过
};
配置package.json
"config": {
"commitizen": {
"path": "cz-customizable"
}
}
安装
npm install husky lint-staged -D
配置package.json
"lint-staged": {
"*.{scss,vue}": [
"stylelint --fix"
],
"*.{js,ts,vue}": [
"vue-cli-service lint"
]
},
"gitHooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -eV"
}
代码提交时,使用 npx cz 命令代替 git commit,git add .后直接输入npx cz即可,这样每个人commit message都按着规范提交代码。
提交不规范时会提示,不允许提交