Reputation: 100010
If we have this:
{
"scripts":{
"postinstall":"./scripts/postinstall.sh"
}
}
Then this postinstall hook will run whenever we do an
$ npm install
At the command line
What I am wondering however, is if there is a way to run a postinstall hook when we install a dependency like this
$ npm install x
Is there some NPM hook that we can use for that?
Upvotes: 2
Views: 2536
Reputation: 24992
Short answer There's no functionality built-in to npm which provides this kind of hook that I'm aware of.
Possible solution, albeit a bash one, would be to completely override the npm install x
command with your own custom logic. For example:
Create a .sh
script as follows. Lets name the file 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
}
Add the following snippet to your .bash_profile
file ( Note: you'll need to define the actual path to 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
After configuring your .bash_proile
as per point two above, you'll need to create a new terminal session/window for it to be effective. The logic will be effective in all terminal sessions thereafter.
Now, whenever you run npm install <name>
or the many other variations such as:
npm install <name>@<version>
npm install <name> <name> --save-dev
npm i -D <name>
custom-npm-install.sh
will run the command as per normal and then run the command ./scripts/postinstall.sh
(i.e. whatever the subsequently given command is set to).
All other npm commands will be run as normal, e.g. npm install
Given custom-npm-install.sh
current logic the ./scripts/postinstall.sh
will be run whenever npm install <name> ...
is entered via the CLI. However, if you wanted it to run ONLY when a specific package is installed then you'll need to change the conditional logic in the if
statement. For example if you want ./scripts/postinstall.sh
to run ONLY when installing shelljs
then change the if
statement to:
if [[ $* == "install "*" shelljs"* || $* == "i "*" shelljs"* ]];
Upvotes: 2