起因
无意间遇到一个 npm 包 husky,它可以管理 git 的 hooks 工具,使用方法如下:
npm install husky -D
然后修改 package.json,增加配置:
{
"scripts": {
"precommit": "eslint src/**/*.js"
}
}
最后尝试 Git 提交,你就会很快收到反馈:
git commit -m "Keep calm and commit"
那么问题来了:husky 什么时候安装 git-hooks 插件的?
npm hooks
经过一番查找,才发现 npm 原来有 hooks 这个功能。它们都可以在 package.json 的 scripts 属性里定义,并且会在生命周期的某个指定时刻被执行,这就是上面提到的“对外部发来的消息也能拦截处理”,这极大的方便了开发人员(或许你想做点坏事儿?)
-
prepublish: 在
publish该包之前执行。(在包目录下执行npm install时也会执行) -
postpublish: 在该包
publish之后执行 -
preinstall: 在该包被
install之前执行 -
postinstall: 在该包被
install之后执行 -
preuninstall: 在该包被
uninstall之前执行 -
postuninstall: 在该包被
uninstall之后执行 -
preversion: 在修改该包的
version之前执行 -
postversion: 在修改该包的
version之后执行 -
pretest, posttest: 在该包内执行
test时执行,其中pretest先于posttest -
prestop, poststop: 在该包内执行
stop时执行,其中prestop先于poststop -
prestart,poststart: 在该包内执行
start时执行,其中prestart先于poststart -
prerestart, postrestart: 在该包内执行
restart脚本时执行,其中prerestart先于postrestart。注意: 如果没有在scripts里显示指定restart脚本,则会自动调用stop,然后再start
上面这些 Hooks 都是 npm 预定义好的,也就是说,当你执行 npm install 时,如果你在 scripts 里定义了 preinstall 和 postinstall,那它们分别会在 npm install 之前/后自动执行,不劳你操心!碉堡了,有木有?
还有,任何自定义脚本(通过 npm run <脚本名>来执行)也可以前缀 pre 和 post 为其制作钩子。比如:premyscript,myscript,postmyscript脚本名>
结论
在 husky 的 package.json 中:
{
"scripts": {
"test": "npm run lint && jest",
"_install": "node husky install",
"preuninstall": "node husky uninstall",
"devinstall": "npm run build && npm run _install -- node_modules/husky && node scripts/dev-fix-path",
"devuninstall": "npm run build && npm run preuninstall -- node_modules/husky",
"build": "del-cli lib && tsc",
"version": "jest -u && git add -A src/installer/__tests__/__snapshots__",
"postversion": "git push && git push --tags",
"prepublishOnly": "npm run test && npm run build && pinst --enable && pkg-ok",
"postpublish": "pinst --disable",
"lint": "tslint 'src/**/*.ts'",
"fix": "npm run lint -- --fix"
},
}
在 husky 安装时会执行 devintall 这个 npm hooks,所以安装后就可以直接 git hooks 了