【发布时间】:2018-08-05 15:13:17
【问题描述】:
如果我们有这个:
{
"scripts":{
"postinstall":"./scripts/postinstall.sh"
}
}
然后这个 postinstall 钩子将在我们执行时运行
$ npm install
在命令行
然而,我想知道的是,当我们安装这样的依赖项时,是否有办法运行安装后挂钩
$ npm install x
有没有我们可以使用的 NPM 钩子?
【问题讨论】:
如果我们有这个:
{
"scripts":{
"postinstall":"./scripts/postinstall.sh"
}
}
然后这个 postinstall 钩子将在我们执行时运行
$ npm install
在命令行
然而,我想知道的是,当我们安装这样的依赖项时,是否有办法运行安装后挂钩
$ npm install x
有没有我们可以使用的 NPM 钩子?
【问题讨论】:
简短回答我知道,npm 没有内置功能可以提供这种钩子。
可能的解决方案,尽管是一个 bash 解决方案,但将使用您自己的自定义逻辑完全覆盖 npm install x 命令。例如:
如下创建.sh 脚本。让我们将文件命名为custom-npm-install.sh:
#!/usr/bin/env bash
npm() {
if [[ $* == "install "* || $* == "i "* ]]; then
# When running `$ npm install <name>` (i.e. `$ npm install ...` followed
# by a space char and some other chars such as a package name - run
# the command provided.
command npm "$@"
# Then run a pseudo `postinstall` command, such as another shell script.
command path/to/postinstall.sh
else
# Run the `$ npm install` command and all others as per normal.
command npm "$@"
fi
}
将以下 sn-p 添加到您的 .bash_profile 文件中(注意:您需要定义到 custom-npm-install.sh 的实际路径):
# Custom logic applied when the `npm install <name>` or the
# shorthand equivalent `npm i <name>` command is run.
. path/to/custom-npm-install.sh
备注
按照上述第二点配置您的.bash_proile 后,您需要创建一个新的终端会话/窗口以使其生效。该逻辑将在此后的所有终端会话中生效。
现在,无论何时运行 npm install <name> 或许多其他变体,例如:
npm install <name>@<version>npm install <name> <name> --save-devnpm i -D <name>custom-npm-install.sh 将照常运行命令,然后运行命令./scripts/postinstall.sh(即,随后给定的命令设置为什么)。
所有其他 npm 命令将正常运行,例如npm install
给定custom-npm-install.sh 当前逻辑,只要通过 CLI 输入npm install <name> ...,./scripts/postinstall.sh 就会运行。但是,如果您希望它在安装特定软件包时运行ONLY,那么您需要更改if 语句中的条件逻辑。例如,如果您希望./scripts/postinstall.sh 在安装shelljs 时运行ONLY,则将if 语句更改为:
if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];
【讨论】:
npm link。但是在这样做之后,如果您在项目中运行npm install x,它通常会破坏符号链接。所以我需要一种在安装后重新符号链接项目的方法。所以重新符号链接会在 npm install x 的安装后脚本中发生。
npm-link-up,但我实际上认为nlu 更胜一筹——Lerna 是 Babel 团队创建的,因此获得了更多曝光。