第一步:安装依赖
- 安装 commitlint 工具和规则集。
npm install --save-dev @commitlint/cli @commitlint/config-conventional
- 安装 husky 用于 git 拦截
(如果安装失败需检查node版本,需要node10以上)
npm i husky -D
第二步:增加 commitlint 配置文件
- 在根目录新增 commitlint.config.js 当然也可以是 .commitlintrc.js 文件,并增加以下配置:
module.exports = { extends: ['@commitlint/config-conventional'] };
或者一键生成配置文件
echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js
- 增加中文配置文件,新建 .cz-config.js 文件,复制以下代码:
'use strict';
module.exports = {
types: [
{value: 'feat', name: 'feat:增加了新功能'},
{value: 'fix', name: 'fix:修复bug'},
{value: 'docs', name: 'docs:只改动了文档相关的内容'},
{value: 'style', name: 'style:与代码逻辑无关的改动,例如删除空格、改变缩进、增删分号等',},
{value: 'refactor', name: 'refactor:代码重构,与bug修复和新功能无关',},
{value: 'perf', name: 'perf:优化相关,比如提升性能、体验',},
{value: 'test', name: 'test:测试用例,包括单元测试、集成测试等'},
{value: 'chore', name: 'chore:改变构建流程、或者增加依赖库、工具等',},
{value: 'revert', name: 'revert:版本回滚'},
],
// override the messages, defaults are as follows
messages: {
type: '选择一种你的提交类型:',
scope: '选择一个scope (可选):',
// used if allowCustomScopes is true
customScope: 'Denote the SCOPE of this change:',
subject: '短说明:\n',
body: '长说明,使用"|"换行(可选):\n',
breaking: '非兼容性说明 (可选):\n',
footer: '关联关闭的issue,例如:#31, #34(可选):\n',
confirmCommit: '确定提交说明?'
},
allowCustomScopes: true,
allowBreakingChanges: ['特性', '修复'],
subjectLimit: 100
};
第三步:配置拦截
在 package.json 中增加以下配置项
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
},
第四步:配置完成
以上三步,配置完成,接下来遵守提交规范,不然提交不上去。以下是提交示例:
// <type>(<scope>): <subject>
git commit -m 'feat(package.json): commitlint 拦截增加'
Tip: 如果项目中使用了 eslint 和 ts ,有可能以上两个文件会报以下错误:
Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser.
解决方案:在 tsconfig.json 中增加以下配置:
"include": [
"mock/**/*",
"src/**/*",
"config/**/*",
".umirc.ts",
"typings.d.ts",
".commitlintrc.js", // 主要是这两个
".cz-config.js", // 主要是这两个
".eslintrc.js",
".prettierrc.js"
],