Commitizen规范git提交代码
首先全局安装Commitizen,运行:
npm install -g commitizen
然后在项目中开启终端,安装cz-customizable
npm i cz-customizable --save-dev
然后在package.json中配置如下代码:
"config": {"commitizen": {"path": "node_modules/cz-customizable"}
}
然后在根目录中新建.cz-config.js文件,进行如下配置:
module.exports = {// 可选类型types: [{ value: "feat", name: "feat: 新功能" },{ value: "fix", name: "fix: 修复" },{ value: "docs", name: "docs: 文档变更" },{ value: "style", name: "style: 代码格式(不影响代码运行的变动)" },{value: "refactor",name: "refactor: 重构(既不是增加feature,也不是修复bug)",},{ value: "perf", name: "perf: 性能优化" },{ value: "test", name: "test: 增加测试" },{ value: "chore", name: "chore: 构建过程或辅助工具的变动" },{ value: "revert", name: "revert: 回退" },{ value: "build", name: "build: 打包" },],// 消息步骤messages: {type: "请选择提交类型:",customScope: "请输入修改范围(可选):",subject: "请简要描述提交(必填):",body: "请输入详细描述(可选):",footer: "请输入要关闭的issue(可选):",confirmCommit: "确认使用以上信息提交?(y/n/e/h)",},// 跳过问题skipQuestions: ["body", "footer"],// subject文字长度默认是72subjectLimit: 72,
};
然后我们就来git提交下:
- git add .
- git cz => 使用 `git cz` 代替 `git commit`,即可看到提示内容
- git push
扩展:设置强制性Commitizen规范提交,否则拦截报错
使用 husky + commitlint 检查提交描述是否符合规范要求
项目控制台安装依赖:
npm install --save-dev @commitlint/config-conventional @commitlint/cli
运行:根目录创建commitlint.config.js,并设置进行配置
module.exports = {// 继承的规则extends: ['@commitlint/config-conventional'],// 定义规则类型rules: {// type 类型定义,表示 git 提交的 type 必须在以下类型范围内'type-enum': [2,'always',['feat', // 新功能 feature'fix', // 修复 bug'docs', // 文档注释'style', // 代码格式(不影响代码运行的变动)'refactor', // 重构(既不增加新功能,也不是修复bug)'perf', // 性能优化'test', // 增加测试'chore', // 构建过程或辅助工具的变动'revert', // 回退'build' // 打包]],// subject 大小写不做校验'subject-case': [0]}}
再次安装依赖:
npm install husky --save-dev
运行:会自动生成一个`.husky` 文件夹
npx husky install
然后再运行:会在package.json中生成 `prepare` 指令
npm set-script prepare "husky install"
接着依次运行:
npm run preparenpx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
就成了,我们现在来测试一下:
- git add .
- git commit -m "测试"
- git cz
- git push