commitlint配置教程
commitlint
是一个用于帮助团队定义和强制执行一致的 Git commit 消息格式的工具。它可以帮助确保代码提交信息具有清晰的格式和有意义的描述,从而提高代码的可读性和可维护性。以下是一个简单的 commitlint
教程,指导你如何设置和使用它。
1. 安装 commitlint
首先,你需要在你的项目中安装 commitlint
及其依赖。你可以使用 npm 或 yarn 进行安装:
npm install --save-dev @commitlint/config-conventional @commitlint/cli
# 或者
yarn add --dev @commitlint/config-conventional @commitlint/cli
这里我们安装了 @commitlint/config-conventional
,这是一个基于常规提交(Conventional Commits)规范的配置。
2. 配置 commitlint
在项目的根目录下创建一个名为 .commitlintrc.js
的文件,并添加以下内容:
module.exports = {
extends: ['@commitlint/config-conventional'],
};
这个配置文件告诉 commitlint
使用常规提交规范进行校验。
3. 设置 Git Hook
为了确保每次提交都符合规范,你可以设置一个 Git Hook,在提交之前运行 commitlint
。这可以通过在 .git/hooks/commit-msg
文件中添加代码来实现,但更常见的做法是使用工具如 husky
来管理 Git Hooks。
首先,安装 husky
:
npm install --save-dev husky
# 或者
yarn add --dev husky
然后,在你的 package.json
文件中添加以下配置:
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
这样,每次你尝试提交代码时,husky
都会运行 commitlint
对提交信息进行校验。
4. 编写符合规范的提交信息
现在,当你尝试提交代码时,你需要编写符合常规提交规范的提交信息。常规提交规范通常遵循以下格式:
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
<type>
:提交类型(如feat
、fix
、docs
等)<scope>
:可选,描述提交影响的范围(如模块名、包名等)<subject>
:简短描述提交的内容<body>
:可选,详细描述提交的内容,可以包含多行<footer>
:可选,包含与提交相关的元数据(如 Breaking Changes、JIRA 票据等)
例如:
feat(button): add primary button style
Add a new primary button style to the button component.
BREAKING CHANGE: The old button style has been removed.
5. 提交并验证
现在,当你尝试提交代码时,commitlint
会根据你在 .commitlintrc.js
文件中配置的规范对提交信息进行校验。如果提交信息不符合规范,commitlint
会报错并阻止提交。确保你的提交信息符合规范后,再次尝试提交即可。
实例:
$ git commit -m '这是一个不合规的提交信息'
husky > commit-msg (node v16.6.0)
⧗ input: update
✖ subject may not be empty [subject-empty]
✖ type may not be empty [type-empty]
✖ found 2 problems, 0 warnings
ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
husky > commit-msg hook failed (add --no-verify to bypass)
$ git commit -m 'feat: 这是一个合规的提交信息'
husky > commit-msg (node v16.6.0)
[dev afec4a9] feat: 这是一个合规的提交信息
2 files changed, 1075 insertions(+), 570 deletions(-)
本文地址:https://www.tides.cn/p_node-commitlint-config