lerna项目中优雅地集成husky、lint-staged、commitlint和cz-customizable
2023-12-20 18:09:14
在单仓库多package的项目中,lerna是一个非常受欢迎的解决方案,它可以帮助我们轻松管理多个子项目。而为了保证代码质量和提交规范,我们需要使用一些工具来辅助我们。其中,husky、lint-staged、commitlint和cz-customizable都是非常实用的工具。
husky是一个Git钩子管理器,它可以让我们在提交代码时执行一些自定义脚本。lint-staged可以帮助我们在暂存区提交代码之前对代码进行检查,确保代码符合我们的代码风格和质量要求。commitlint可以帮助我们规范提交信息,确保提交信息清晰、准确。cz-customizable可以帮助我们自定义提交信息模板,使提交信息更加统一和美观。
在lerna项目中,我们可以使用lerna-husky这个工具来轻松集成husky、lint-staged、commitlint和cz-customizable。lerna-husky是一个专门为lerna项目设计的husky插件,它可以让我们轻松地在lerna项目中使用husky。
首先,我们需要在lerna项目中安装lerna-husky:
npm install --save-dev lerna-husky
然后,我们需要在lerna项目的package.json文件中添加如下配置:
{
"scripts": {
"prepare": "lerna run prepare",
"precommit": "lerna run precommit",
"prepush": "lerna run prepush"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"pre-push": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
在上面的配置中,我们首先定义了三个脚本:prepare、precommit和prepush。prepare脚本会在lerna项目准备发布时执行,precommit脚本会在提交代码时执行,prepush脚本会在推送代码时执行。
然后,我们在husky的hooks配置中指定了pre-commit和pre-push钩子。pre-commit钩子会在提交代码时执行lint-staged,pre-push钩子会在推送代码时执行commitlint。
接下来,我们需要在lerna项目中安装lint-staged、commitlint和cz-customizable:
npm install --save-dev lint-staged commitlint cz-customizable
然后,我们需要在lerna项目的.lintstagedrc文件中添加如下配置:
{
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"stylelint --fix"
]
}
在上面的配置中,我们指定了需要被lint的文件类型以及需要执行的lint命令。
然后,我们需要在lerna项目的.commitlintrc.js文件中添加如下配置:
module.exports = {
rules: {
"body-leading-blank": [1, "always"],
"body-max-line-length": [2, "always", 100],
"footer-leading-blank": [1, "always"],
"footer-max-line-length": [2, "always", 100],
"header-max-length": [2, "always", 100],
"subject-case": [2, "always", "sentence-case"],
"subject-empty": [2, "never"],
"subject-full-stop": [2, "never"],
"type-case": [2, "always", "lower-case"],
"type-empty": [2, "never"],
"type-enum": [
2,
"always",
[
"build",
"ci",
"chore",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test"
]
]
}
};
在上面的配置中,我们指定了提交信息的格式和规范。
然后,我们需要在lerna项目的.cz-config.js文件中添加如下配置:
module.exports = {
types: [
{ value: "feat", name: "✨ New Feature" },
{ value: "fix", name: "🐛 Fix" },
{ value: "refactor", name: "🔨 Refactor" },
{ value: "docs", name: "📝 Documentation" },
{ value: "test", name: "✔️ Tests" },
{ value: "style", name: "💄 Style" },
{ value: "build", name: "👷 Build" },
{ value: "ci", name: "🤖 CI" },
{ value: "chore", name: "🧹 Chore" },
{ value: "revert", name: "⏪ Revert" },
{ value: "perf", name: "🚀 Performance" }
]
};
在上面的配置中,我们指定了提交信息的类型以及对应的名称。
现在,我们就可以在lerna项目中优雅地使用husky、lint-staged、commitlint和cz-customizable了。在提交代码时,husky会自动执行lint-staged和commitlint,确保代码符合我们的代码风格和质量要求,以及提交信息的格式和规范。