如果我们有:
{
"scripts":{
"postinstall":"./scripts/postinstall.sh"
}
}
然后,每当我们做
$ 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
文件(注意:您需要定义到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-dev
-
npm i -D <name>
- 等,等...
custom-npm-install.sh
将按照正常运行命令,然后运行命令./scripts/postinstall.sh
(即,随后给定的命令设置为什么(。 -
-
所有其他NPM命令将按照正常运行,例如
npm install
-
给定的
custom-npm-install.sh
当前逻辑,每当通过CLI输入npm install <name> ...
时,./scripts/postinstall.sh
将运行。但是,如果您希望它仅运行在安装特定软件包时,则需要在if
语句中更改条件逻辑。例如,如果您希望./scripts/postinstall.sh
在安装shelljs
时仅运行,则将if
语句更改为:if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];