我的个人博客

Conventional Commit 提交规范介绍

Person typing on apple keyboard
Published on
/6 mins read/---

介绍

Conventional commit 是一种特定的提交形式,为软件开发者提供了一个统一的系统来组织和描述他们的更改,使跟踪更新变得更加容易。 这种类型的提交通常遵循严格且一致的格式,使理解所做的更改及其原因变得更加容易。

conventional commit 通常遵循特定的格式,例如:

<type>[optional scope]: <description>

其中 type 是提交的主题,它表示所做更改的类型,应该是以下类型之一:

  • feat: 一个特性或项目的新增功能
  • fix: 修复bug
  • refactor: 代码重构或项目基础设施的更改
  • style: 格式、空格等的更改
  • docs: 文档更改
  • perf: 提高性能的代码更改
  • chore: 次要更改,如更新依赖版本、修复拼写错误等
  • ...

scope 是可选的,用于指示项目中被更改的部分,如 apiuidatabase 等。

description 是对更改的简短描述,应该使用祈使语气编写,如"change"而不是"changed"或"changes"。

示例:

feat(api): send an email to the customer when a product is shipped

fix: prevent racing of requests

为什么使用 conventional commit?

Conventional commit 有助于确保提交是有组织且一致的。这使得阅读和理解所做的更改及其原因变得更加容易。它还使跟踪和理解相关问题和拉取请求变得更加容易。

通过遵循 conventional commit 格式,团队还可以轻松创建遵循相同结构和格式的提交消息。这使得审查和理解所做的更改变得更加容易,并确保每次更改都以相同的方式记录。

此外,conventional commit 是保持项目代码库有组织和一致性的好方法。这有助于确保代码库易于维护和阅读,并减少花在调试和重构上的时间。

在项目中设置 conventional commit

在这篇文章中,我将向你展示如何使用 commitlint 在你的项目中设置 conventional commit。

安装 commitlint 及其依赖项:

npm install -g @commitlint/cli @commitlint/config-conventional

向你的项目添加 commitlint 配置文件:

使用此命令创建具有基本配置的配置文件:

echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js

该文件应具有以下内容:

commitlintcommitlint.config.js
module.exports = { extends: ['@commitlint/config-conventional'] }

添加 husky 以在创建提交前对其进行检查:

npm install husky --save-dev

使用以下命令激活钩子:

npx husky install

你应该看到以下输出:

husky - Git hooks installed

并且在项目根目录中应该创建一个新的 .husky 文件夹。

我强烈建议在 package.json 文件中添加一个 postinstall 脚本,以在安装依赖项后自动安装 husky 钩子:

"scripts": {
	"postinstall": "husky install"
}

添加一个 commit-msg 钩子来检查提交:

npx husky add .husky/commit-msg  'npx --no -- commitlint --edit ${1}'

你应该看到在 .husky 文件夹中创建了一个 commit-msg 文件。

就是这样 !现在,每当你提交时,commitlint 将检查你的提交消息,并确保它遵循 conventional commit 格式。

让我们尝试一个非常规的提交消息:

git commit -m "Using commitlint and husky to lint commits"

提交应该失败,并显示以下错误:

   input: Using commitlint and husky to lint commits
   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 exited with code 1 (error)

如你所见,commitlint 已检测到提交消息不遵循 conventional commit 格式,并提供了有用的错误消息。

现在,让我们再次尝试使用 conventional commit 消息:

git commit -m "feat: add commitlint and husky to lint commits"

提交应该成功,并显示以下输出:

[main b40785f] feat: using husky to lint commits
	3 files changed, 27 insertions(+)
	create mode 100755 .husky/commit-msg

结论

Conventional commit 是确保提交消息有组织且一致的好方法。 通过遵循 conventional commit 格式, 团队可以轻松创建遵循相同结构和格式的提交消息, 使审查和理解所做的更改变得更加容易。

因此,在开发项目时使用这种类型的提交很重要,这样更改就能得到良好的记录和跟踪。

愉快的提交