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

后端 未结 5 1693
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 19:03

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 inst

相关标签:
5条回答
  • 2020-12-30 19:48

    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
    
    0 讨论(0)
  • 2020-12-30 19:49

    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.

    0 讨论(0)
  • 2020-12-30 19:53
    [ $(node -p "try{require('protractor/package.json').version}catch(e){}") != "2.1.0" ]  && npm install grunt
    
    0 讨论(0)
  • 2020-12-30 19:55

    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

    0 讨论(0)
  • 2020-12-30 19:57

    with bash you can do

    [ $(node -p "require('protractor/package.json').version") != "2.1.0" ] && npm install protractor@2.1.0
    
    0 讨论(0)
提交回复
热议问题