npm script 的 pre、post 钩子及在 pre commit 时进行 lint
pre、post 钩子
介绍
npm run为每条命令提供了pre-和post-两个钩子(hook)。- 以
npm run lint为例,执行这条命令之前,npm会先查看有没有定义prelint和postlint两个钩子,如果有的话,就会先执行npm run prelint,然后执行npm run lint,最后执行npm run postlint - 可以在这两个钩子中来完成一些其它事情,如在执行
test前先执行lint操作
示例
1 | "scripts": { |
- 执行
npm run test时会先执行npm run pretest再执行npm run test最后执行npm run posttest - 中间任意一环节报错,就会中断后续执行
- 不能在
pre脚本之前再加pre,即prepretest脚本不起作用。 - 即使
npm可以自动运行pre和post脚本,也可以手动执行它们
缺陷
pre、post钩子只能在npm run时生效,没法在其他场景使用;- 如需要在
git commit时先lint代码
改进
- 使用
husky
husky
介绍
husky可以在git commit和git push时执行自定义脚本- 可以利用这个特性在
commit时做lint工作
示例
1 | "scripts": { |
注意
- 老版本
husky的钩子是直接定义在scripts中的,最新版本将其转移到husky字段下了 - 老版本
husky的钩子名称一般为precommit、prepush,现在统一改成了pre-commit、pre-push
缺点
- 每次针对所有文件进行
lint,我们希望仅针对修改的或者说是staged的文件进行lint-husky配合lint-staged使用
lint-staged
介绍
husky可以让我们在git commit和git push时执行一段脚本lint-staged则可以针对add进git 暂存区的文件进行lint操作
使用
- 首先安装
npm i -D lint-staged husky
- 定义
lint-staged相关脚本- 可针对不同类型文件执行不同脚本,参考示例
示例
1 | "scripts": { |