git Hook
git hook (git钩子||git 回调)

使用 husky + commitlint 检查提交描述是否符合规范要求
使用git hook去校验我们的提交信息,需要用到两个工具
1、commitlint:用于检查提交信息
2、husky:是git hooks工具
注意:npm需要在7.x以上版本
commitlint
1、安装依赖
npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4
2、创建commitlint.config.js文件,也可以直接在终端输入
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
3、打开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]
}
}
注意:确保格式是utf-8,否则会报错
husky
1、安装依赖
npm install husky@7.0.1 --save-dev
2、启动hooks,生成.husky文件夹
npx husky install
3、在package.json中生成prepare指令(npm需要在7.x以上版本)
npm set-script prepare "husky install"
4、执行prepare指令
npm run prepare
5、添加commitlint的hook到husky中,并指令在commit-msg的hooks下执行npx --no-install commitlint --edit "$1"的指令
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
6、

至此,不符合规范的commit将不再可提交
通过 pre-commit 检测提交时代码规范
我们期望通过 husky 监测 pre-commit 钩子,在该钩子下执行 npx eslint --ext .js,.vue src 指令来去进行相关检测:
1、执行 npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src" 添加 commit 时的 hook (npx eslint --ext .js,.vue src 会在执行到该 hook 时运行)(window用户直接2)
2、手动创建pre-commit文件,并填入以下内容
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx eslint --ext .js,.vue src
3、关闭 VSCode 的自动保存操作
4、修改一处代码,使其不符合 ESLint 校验规则
5、执行 提交操作 会发现,抛出一系列的错误,代码无法提交
如果抛出很多的 ESLint 错误怎么办,有没有办法可以 ”自动“ 帮助他修复对应的问题,并且完成提交呢?
lint-staged 自动修复格式错误
pre-commit 处理了 检测代码的提交规范问题,当我们进行代码提交时,会检测所有的代码格式规范 。
但是这样会存在两个问题:
1、我们只修改了个别的文件,没有必要检测所有的文件代码格式
2、它只能给我们提示出对应的错误,我们还需要手动的进行代码修改
需要使用另外一个插件 lint-staged !
npm i lint-staged --legacy-peer-deps
lint-staged 可以让你当前的代码检查 只检查本次修改更新的代码,并在出现错误的时候,自动修复并且推送
lint-staged 无需单独安装,我们生成项目时,vue-cli
已经帮助我们安装过了,所以我们直接使用就可以了
1、修改 package.json 配置
"lint-staged": {
"src/**/*.{js,vue}": [
"eslint --fix",
"git add"
]
}
2、修改 .husky/pre-commit 文件
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged