NPM 预安装脚本 [英] NPM preinstall script

查看:37
本文介绍了NPM 预安装脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在安装任何软件包之前运行一些监管脚本.例如:

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"
  }
}

似乎上面示例中的安装前和安装后脚本仅在我执行 npm install 时才有效,但我希望每次尝试安装任何东西时都能运行该脚本.

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.

例如:假设我想编写一个脚本来在我的团队运行 npm install 时随时检查包的版本.我想检查安装包的版本并确认它的版本高于1.0.0",否则不要让他们安装.

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 信息 lodash 版本

并检查我尝试安装的任何软件包的版本.如果版本不可用,我计划使其具有交互性并在安装前询问用户的确认.

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.

推荐答案

你说得对,预安装脚本只在我们执行 npm install 时运行,目前没有办法在安装模块之前运行脚本,但你可以使用 shell 脚本npm 视图https://docs.npmjs.com/cli/view 这样做.

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 .

首先,创建一个 moduleinstall.sh 文件,它与你的 package.json 和下面的 shell 脚本具有相同的范围

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

确保使用 chmod +x moduleinstall.sh 使其可执行,然后将其写入 package.json

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"
}

现在您只需要运行命令 npm run info 然后按照说明通过检查版本来安装模块.您可以使用 npm 视图和 shell 脚本的不同选项来推进它.希望这会有所帮助.

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.

这篇关于NPM 预安装脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆