前言
在日常工作中,我们有时会无法避免的使用 git, 那么我们如何确保我们提交代码时的 commit 信息规范,且我们提交上去的代码在 CI 过程中能正常进行。
工具
commitizen-- 当你在使用git commit提交时,Commitizen 能够快速地帮你完成提交信息的补充。husky-- git hook 助手, 支持所有的 git hookcommitlint-- 用于校验填写的commit message是否符合设定的规范
使用 Commitizen
安装
npm install -g commitizen
非全局安装使用,请参考官网 https://www.npmjs.com/package/commitizen
安装规范配置:
# npm
commitizen init cz-conventional-changelog --save-dev --save-exact
# yarn
commitizen init cz-conventional-changelog --yarn --dev --exact
# pnpm
commitizen init cz-conventional-changelog --pnpm --save-dev --save-exact
注意: 覆盖安装请使用 --force 参数
上面命令做了如下三件事
- 安装
cz-conventional-changelog模块 - 将
cz-conventional-changelog保存在dependencies或devDependencies - 将
config.commitizen密钥添加到package.json文件的根目录
{
...
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}
注: 也可以配置 .czrc 文件
{
"path": "./node_modules/cz-conventional-changelog"
}
使用
// git add your change file
git cz // 别名 git-cz or cz
在执行如上命令后,交互式命令框会提示你选择项目维护者配置的必填提交规范(默认使用的是 Angular 团队的提交规范):
git cz 会记录最后一次 commit, git cz --retry
使用 Husky
husky git hook 工具库
官网地址: typicode.github.io/husky/#/?id…
作用: 可以在提交前 运行 测试代码, lint 代码等
husky 完全支持 git hooks 钩子
安装
npm install husky --save-dev
使用:
husky-init 是一个一次性命令,用于快速初始化husky项目。
# npm
npx husky-init && npm install
# Yarn 1
npx husky-init && yarn
# Yarn 2+
yarn dlx husky-init --yarn2 && yarn
# pnpm
pnpm dlx husky-init && pnpm install
安装后自动使用:
- npm 或者 monorepo 项目,在 package.json 中添加如下代码
{
...
"scripts": {
"prepare": "husky install"
}
}
- yarn 项目, 在 package.json 中添加如下代码
注:yarn2+ 不支持 prepare 脚本, 因此需要使用如下配置
{
...
"scripts": {
"postinstall": "husky install"
}
}
禁用自动使用
原因: 如果正在开发的包需要供第三方使用,那么则需要禁用自动使用,否则当别人安装该软件包时, postinstall会执行并且会导致错误
在package.json 中添加如下代码
{
...
"private": false, // ← your package is public
"scripts": {
...
"postinstall": "husky install",
"prepack": "pinst --disable",
"postpack": "pinst --enable"
}
}
也可以使用脚本化安装
"prepare": "node ./prepare.js"
// prepare.js
const isCi = process.env.CI !== undefined
if (!isCi) {
require('husky').install()
}
卸载
npm uninstall husky && git config --unset core.hooksPath
使用 commitlint
安装
npm install --save-dev @commitlint/config-conventional @commitlint/cli
配置
- 根目录下创建
commitlint.config.js | .commitlintrc.js等 - 配置文件
module.exports = {
extends: ['@commitlint/config-conventional']
}
- 在commit-msg hooks 中 添加如下代码
npx --no -- commitlint --edit ${1}
具体配置可参考官网 commitlint.js.org/#/reference…