How to specify/enforce a specific node.js version to use in package.json?

后端 未结 4 2171
北荒
北荒 2021-02-07 06:35

I am searching for a way to break the build, if a user is using a different node.js version as defined in the project.

Ideally to put some checks in grunt or bower or np

相关标签:
4条回答
  • 2021-02-07 06:54

    If you want to enforce a specific version of npm, you might use: https://github.com/hansl/npm-enforce-version

    If you want to enforce a version of node when executing you can read the version of node that is currently running by checking against:

    process.versions

    For more info: https://nodejs.org/api/process.html#process_process_versions

    0 讨论(0)
  • 2021-02-07 07:04

    You can use the "engineStrict" property in your package.json

    Check the docs for more information: https://docs.npmjs.com/files/package.json

    Update on 23rd June 2019

    "engineStrict" property is removed in npm 3.0.0.

    Reference : https://docs.npmjs.com/files/package.json#enginestrict

    0 讨论(0)
  • 2021-02-07 07:06

    "engineStrict" has been removed and "engines" only works for dependencies. If you want to check Node's runtime version this can work for you:

    You call this function in your server side code. It uses a regex to check Node's runtime version using eremzeit's response It will throw an error if it's not using the appropriate version:

    const checkNodeVersion = version => {
      const versionRegex = new RegExp(`^${version}\\..*`);
      const versionCorrect = process.versions.node.match(versionRegex);
      if (!versionCorrect) {
        throw Error(
          `Running on wrong Nodejs version. Please upgrade the node runtime to version ${version}`
        );
      }
    };
    

    usage:

    checkNodeVersion(8)
    
    0 讨论(0)
  • You can use the engines property in the package.json file

    For example, if you want to make sure that you have a minimum of node.js version 6.9 and a maximum of 6.10, then you can specify the following

    package.json
    {
        "name": "Foo",
        ....
        "engines": {
            "node": ">=6.9 <=6.10"
        }
    }
    
    0 讨论(0)
提交回复
热议问题