如何使用 Commitlint 和 Husky 验证提交消息规范
在团队协作中,提交信息非常重要,它可以让其他成员了解你的工作内容。即使团队已经达成共识,有时也可能会出现一些错误👀
在这里我将展示如何在提交之前验证提交消息,并制定约定规则。
让我们来了解一下彼此之间的依赖关系。
💥使用 Husky 的 GitHooks
Git Hooks 是 Git 的一个高效功能,可以帮助我们在某些事件(例如提交、合并、推送等)之前或之后执行脚本或程序。
所以我们需要使用 commit-msg 钩子来验证消息。
为什么要使用 Husky?
你需要在项目中设置这些钩子,以确保其他成员使用该约定。Husky 正好可以解决这个问题,
它提供了一个配置,让我们可以在 package.json 文件中进行设置。
安装 Husky
👉npm install husky --save-dev
设置配置
// package.json
{
"husky": {
"hooks": {
"commit-msg": "excute validation script here"
}
}
}
💥提交Lint &&提交命令行
commitlint 基于通用规范的 lint 消息。
默认情况下,它使用约定式提交,这是约定式提交仓库。
此外,您还可以使用其他约定,例如Angular 提交约定,或者使用贡献者创建的约定,例如Jira 约定。
安装 commitlint 命令行工具和常规配置
👉npm install --save-dev @commitlint/{config-conventional,cli}
Windows 系统适用:
👉npm install --save-dev @commitlint/config-conventional @commitlint/cli
配置 commitlint 使用常规配置
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
这将创建一个名为“配置文件”的文件,commitlint.config.js用于设置要使用的约定。
注意:配置信息取自commitlint.config.js文件commitlintrc.js或.commitlintrc.json应用.commitlintrc.yml程序commitlint field。package.json
现在你需要告诉 Husky 在执行 commit-msg 时使用 Commitlint,方法是编辑 package.json 中的 Husky 对象。
// package.json
{
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
现在一切都已设置完毕,但如果您使用错误的提交信息运行,将会收到如下错误信息。
git commit -m "foo: this will fail"
husky > commit-msg (node v10.1.0)
No staged files match any of provided globs.
⧗ input: foo: this will fail
✖ type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum]
✖ found 1 problems, 0 warnings
ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint
husky > commit-msg hook failed (add --no-verify to bypass)
更详细的设置说明
注意:所有依赖项均已作为开发依赖项安装,您无需将其部署到生产环境。
查看演示
文章来源:https://dev.to/omarzi/how-to-validate-commit-message-convention-using-commitlint-and-husky-aaa