简体   繁体   中英

Yarn Install - how to force the latest minor version and patch of node (10.x.x)

I have a Node app that is tested on node 10. I am using yarn as a dependency manager. As my app test is run on CI with the latest version of node 10, I want to make sure that all developers have installed the latest 10.xx version when running any yarn command.

For example, let's say the current latest node version is 10.22.1, then I want to stop the yarn install if the developer is on 10.22.0 or 10.11.1.

Using the engine directive in package.json I tried the following syntax but no avail.

{
  "engines": {
    "node": "^10.x.x",
  }
}
{
  "engines": {
    "node": "^10",
  }
}
{
  "engines": {
    "node": ">10.0.0 <11.0.0",
  }
}
{
  "engines": {
    "node": "10",
  }
}

All of these allow any node with major version 10.

As per the yarn documentation ( https://classic.yarnpkg.com/en/docs/package-json/ ), the preinstall is called before the package is installed.

If defined, the preinstall script is called by yarn before your package is installed.

So I would go with something like this in your package.json:

"scripts": {
....
    "preinstall": "./scripts/preinstall.sh",
    
  }

Your preinstall.sh could be:

#!/bin/bash
currentver="$(node -v)"
requiredver="v10.0.0"

if [ "$(printf '%s\n' "$requiredver" "$currentver" | sort -V | head -n1)" = "$requiredver" ]; then 
        echo "Version is good so let's go with install"
else
        echo "Please install the node version greater than v10.0.0"
        exit -1
fi
 

So if your developer has a version less than v10.0.0, the above script will fail and will in turn fail the yarn install command.

Note: Credit to https://unix.stackexchange.com/questions/285924/how-to-compare-a-programs-version-in-a-shell-script for shell script for version comparison.

As we have in the npm doc :

to specify acceptable version ranges up to 1.0.4, use the following syntax:

  • Patch releases: 1.0 or 1.0.x or ~1.0.4
  • Minor releases: 1 or 1.x or ^1.0.4
  • Major releases: * or x

So, if you want to ask for only the 10.22.1 version or newer you should use ~10.22.1 or ^10.22.1

And it's another option to pin the version (you can read more about it from this link ) by using the exact version like:

{
  "engines": {
    "node": "10.22.1",
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM