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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:08:17  来源:igfitidea点击:

Is it possible to install npm package only if it has not been already installed?

node.jsbashnpmcircleci

提问by kovpack

Is it possible to install npmpackage 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_modulesfolder with all modules is already present at the moment of running commands (cached from previous build) and protractor --versionetc. 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 protractoris used to find protractorpackage.

wherenpm list protractor用于查找protractor包。

If the package is not found, it will return npm ERR! code 1and do npm install [email protected]for installation

如果没有找到包,它将返回npm ERR! code 1npm 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 开发环境的。

Here is my solution.

这是我的解决方案