husky
手动安装方式
安装 cnpm install husky -D
安装完成后会增加一个.husky文件夹
启用挂钩
npx husky install
安装后自动启用挂钩,编辑packaje.json
npm set-script prepare "husky install" 会新增如下命令
创建一个钩子
npx husky add .husky/pre-commit "npm test"
- 尝试提价 git commit -m "Keep calm and commit"
- 如果
npm test
命令失败,您的提交将自动中止。
对于 Windows 用户,如果您在运行时看到帮助消息
npx husky add ...
,请尝试node node_modules/.bin/husky add ...
改用。这不是 husky 代码的问题,并且在最新版本的 npm 8 中已修复
自动方式安装
npm : npx husky-init && npm install # npm
yarn 2 : yarn dlx husky-init --yarn2 && yarn # Yarn 2
添加一个挂钩
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
使用
- 添加一个npm run lint 挂钩,以及在package.json中增减test 测试命令
"test": "echo "Error: no test specified" && exit 1",
npx husky add .husky/pre-commit "npm run lint"
git add .husky/pre-commit
- 在终端提交代码
这个时候 commit 会自动执行 npm run test 以及 npm run lint 命令,然后才会commit
如果报错
git -c user.useConfigOnly=true commit --quiet --allow-empty-message --file -
注释掉
不写备注也可以提交了
其他
husky
包含很多 hook(钩子),常用有:pre-commit、commit-msg、pre-push
上面这个
pre-commit
hook 文件的作用是:当我们执行 git commit -m "xxx"
时,会先对 src
目录下所有的 .vue、.js、.ts
文件执行 eslint --fix
命令,如果 ESLint
通过,成功 commit
,否则终止 commit
。