如果我们有这个:
{
"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
}
-
将以下代码片段添加到您的.bash_profile
file (注意:您需要定义实际路径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
Notes
配置完你的.bash_proile
根据上面的第二点,您需要创建一个新的终端会话/窗口才能使其有效。该逻辑将在此后的所有终端会话中有效。
-
现在,每当你跑步时npm install <name>
或许多其他变体,例如:
npm install <name>@<version>
npm install <name> <name> --save-dev
npm i -D <name>
- 等等,等等...
custom-npm-install.sh
将正常运行命令,然后运行命令./scripts/postinstall.sh
(即无论随后给定的命令设置为什么)。
所有其他 npm 命令将正常运行,例如npm install
-
Given custom-npm-install.sh
当前逻辑./scripts/postinstall.sh
每当npm install <name> ...
通过 CLI 输入。但是,如果您希望它运行ONLY当安装特定的软件包时,您需要更改中的条件逻辑if
陈述。例如如果你想要./scripts/postinstall.sh
to run ONLY安装时shelljs https://www.npmjs.com/package/shelljs然后改变if
声明至:
if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)