Is it possible to install npm package only if it h

2019-03-22 17:54发布

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

I need this to speed up test on CircleCI, but when I run npm install protractor@2.1.0 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.

Its perfect to have some one-line command like this:

protractor --version || npm install -g protractor@2.1.0

but the one that will also check version of the package.

5条回答
够拽才男人
2楼-- · 2019-03-22 18:05

with bash you can do

[ $(node -p "require('protractor/package.json').version") != "2.1.0" ] && npm install protractor@2.1.0
查看更多
干净又极端
3楼-- · 2019-03-22 18:13
[ $(node -p "try{require('protractor/package.json').version}catch(e){}") != "2.1.0" ]  && npm install grunt
查看更多
仙女界的扛把子
4楼-- · 2019-03-22 18:21

You could try npm list protractor || npm install protractor@2.1.0

Where npm list protractor is used to find protractor package.

If the package is not found, it will return npm ERR! code 1 and do npm install protractor@2.1.0 for installation

查看更多
戒情不戒烟
5楼-- · 2019-03-22 18:21

Function version of the excellent answer by @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:

$ install_package_if_needed protractor 2.1.0 -g
查看更多
来,给爷笑一个
6楼-- · 2019-03-22 18:25

I had this same issue together with wanting to install global dependencies from any "package.json" file requiring them.

This is for a Windows development environment.

Here is my solution.

查看更多
登录 后发表回答