bash 是否可以仅在尚未安装 npm 包的情况下才安装它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30667239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to install npm package only if it has not been already installed?
提问by kovpack
Is it possible to install npm
package only if it has not been already installed?
是否可以npm
仅在尚未安装的情况下安装软件包?
I need this to speed up test on CircleCI, but when I run npm install [email protected]
etc. it always downloads things and installs them from scracth, however, node_modules
folder with all modules is already present at the moment of running commands (cached from previous build) and protractor --version
etc. shows the needed version of the package.
我需要这个来加速 CircleCI 上的测试,但是当我运行npm install [email protected]
等时,它总是从 scracth 下载东西并安装它们,但是,node_modules
在运行命令(从以前的构建中缓存)protractor --version
等时,所有模块的文件夹已经存在。显示所需的软件包版本。
Its perfect to have some one-line command like this:
有一些这样的单行命令是完美的:
protractor --version || npm install -g [email protected]
but the one that will also check version of the package.
但也将检查包的版本。
采纳答案by Jerome WAGNER
with bash you can do
使用 bash 你可以做到
[ $(node -p "require('protractor/package.json').version") != "2.1.0" ] && npm install [email protected]
回答by An Nguyen
You could try npm list protractor || npm install [email protected]
你可以试试 npm list protractor || npm install [email protected]
Where npm list protractor
is used to find protractor
package.
wherenpm list protractor
用于查找protractor
包。
If the package is not found, it will return npm ERR! code 1
and do npm install [email protected]
for installation
如果没有找到包,它将返回npm ERR! code 1
并npm install [email protected]
进行安装
回答by bishop
Function version of the excellent answer by @JeromeWAGNER:
@JeromeWAGNER的优秀答案的功能版本:
function install_package_if_needed() {
local p=${1:-Package required}
local v=${2:-Version required}
shift 2
local i=$(node -p "require('$p/package.json').version" 2>/dev/null)
[ "$i" == "$v" ] || npm "$@" install "$p@$v"
}
Use like:
像这样使用:
$ install_package_if_needed protractor 2.1.0
To pass additional options to npm
, specify them after the version, like so:
要将其他选项传递给npm
,请在版本之后指定它们,如下所示:
$ install_package_if_needed protractor 2.1.0 -g
回答by theJC
[ $(node -p "try{require('protractor/package.json').version}catch(e){}") != "2.1.0" ] && npm install grunt
回答by sthames42
I had this same issue together with wanting to install global dependencies from any "package.json" file requiring them.
我有同样的问题,希望从任何需要它们的“package.json”文件安装全局依赖项。
This is for a Windows development environment.
这是针对 Windows 开发环境的。