如何在VUE项目中安装并使用husky6.x + commitlint 来规范代码的commit提交
husky:
官方文档:https://typicode.github.io/husky/#/
官方的解释是:当我们在提交或者推送代码的时候,可以使用它验证提交信息、运行测试、格式化代码、触发 CI/CD 等。
如何安装并使用
1.安装husky
yarn add husky -D
2.启用git hooks
yarn husky install
3.为了团队可以更好的一起使用husky,我们可以在 package.json 文件的scripts中,安装依赖后启用 git hooks,这样其他开发小伙伴就不需要再次执行以上步骤来使用了
"scripts": {
"postinstall": "husky install"
}
commitlint:
官方文档:https://commitlint.js.org/#/
可以让我们在多人开发中,遵守 git 提交约定。
如何使用:
1.安装依赖
yarn add @commitlint/cli @commitlint/config-conventional -D
2:在对应的项目根目录下建立commitlint.config.js文件
以下是我的config文件中的对应配置,仅供参考。
/**
* feat:新增功能
* fix:bug 修复
* docs:文档更新
* style:不影响程序逻辑的代码修改(修改空白字符,格式缩进,补全缺失的分号等,没有改变代码逻辑)
* refactor:重构代码(既没有新增功能,也没有修复 bug)
* perf:性能, 体验优化
* test:新增测试用例或是更新现有测试
* build:主要目的是修改项目构建系统(例如 glup,webpack,rollup 的配置等)的提交
* ci:主要目的是修改项目继续集成流程(例如 Travis,Jenkins,GitLab CI,Circle等)的提交
* chore:不属于以上类型的其他类型,比如构建流程, 依赖管理
* revert:回滚某个更早之前的提交
*/
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'revert'],
],
'subject-full-stop': [0, 'never'],
'subject-case': [0, 'never'],
},
};
3.增加 commit-msg 勾子:
使用下面命令增加一个 git 提交信息的勾子,会在 .husky 目录下创建一个 commit-msg 文件。
yarn husky add .husky/commit-msg 'yarn commitlint --edit "$1"'
4.重新启动项目,让我们来试试效果如何
yarn run serve
5.尝试不遵守commitlint里进行提交
git add . git commit -m'test: husky'
6.可以看到在git bash中报错了 原因是我们没有test这个命令规范
$ git commit -m'test:husky'
yarn run v1.22.10
$ D:\project\VUE3-TS-Admin-\node_modules\.bin\commitlint --edit .git/COMMIT_EDITMSG
⧗ input: test:husky
✖ 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
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
husky - commit-msg hook exited with code 1 (error)
7.重新安装规范进行commit提交
$ git commit -m'feat: husky and commitlint.config.js'
8.大功告成
$ git commit -m'feat: husky and commitlint.config.js'
yarn run v1.22.10
$ D:\project\VUE3-TS-Admin-\node_modules\.bin\commitlint --edit .git/COMMIT_EDITMSG
Done in 0.54s.
[main 2432eba] feat: husky and commitlint.config.js
5 files changed, 37 insertions(+), 2 deletions(-)
create mode 100644 .husky/.gitignore
create mode 100644 .husky/commit-msg
create mode 100644 commitlint.config.js