问题
I am trying to run some policing script before any packages are installed. For Example:
{
"name": "pre-hook-check",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"preinstall": "echo preinstall",
"postinstall": "echo postinstall"
},
"author": "",
"license": "ISC",
"dependencies": {
"abc": "^0.6.1",
"preact": "^8.2.5"
}
}
It seems the pre and post install script on above example only works when I do npm install
, but I want that to run every time I try to install anything.
For example: Let's say I want to write a script to check for the version of the package any time my team runs npm install <some package>
. I want to check for the version of installing package and verify that it's version is above "1.0.0" else don't let them install.
I was planning to write a preinstall script that goes
npm info lodash version
and checks for the version of any package I am trying to install. If the version is not available, I plan to make it interactive and ask user's acknowledgement before install.
回答1:
You are right the preinstall script runs only when we do npm install and there is currently no way to run a script before installing a module but you can use shell scripting and npm view https://docs.npmjs.com/cli/view to do so .
First , create a moduleinstall.sh file which has the same scope as your package.json and the below shell script to it
echo 'Enter the name of the module'
read module_name
npm view $module_name version
echo "Do you want to install this version(y/N) "
read option
if [ "$option" = "N" ] || [ "$option" = "n" ]
then
echo "exiting...."
exit 1
else
npm install $module_name
fi
make sure you make it executable using chmod +x moduleinstall.sh
and then write this in your package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"info": "./moduleinstall.sh"
}
Now you just have to run the command npm run info
and then follow the instruction to install a module by checking the version . You can advance it using different options of npm view and shell scripting.
Hope this helps.
来源:https://stackoverflow.com/questions/46556921/npm-preinstall-script