Skip to content

npm 脚本钩子

主要用在用户执行对应的脚本的时候从而执行对应的钩子函数。

shell
preinstall    # 用户执行npm install命令时候,先执行脚本
postinstall   # 用户执行npm install命令是,安装结束后执行该脚本
preuninstall  # 卸载一个模块前执行
postuninstall # 卸载一个模块后执行
prelink       # 执行 npm link模块前执行
postlink      # 执行 npm link模块后执行

当然也可以进行自定义钩子

json
{
  "scripts": {
    "serve": "vite",
    "preserve": "node ./scripts/preServe.js",
    "postserve": "node ./scripts/postServe.js"
  }
}

preinstall

在 install 之前执行的钩子,主要用来切换 npm 源等

json
{
  "scripts": {
    "preinstall": "node ./scripts/preinstall.js"
  }
}
js
require("child_process").exec("npm config get registry", function (error, stdout, stderr) {
  if (!stdout.toString().match(/registry\.x\.com/)) {
    exec("npm config set @xscope:registry https://xxx.com/npm/")
  }
})