防止 Node 版本不匹配时运行 npm start

3
我有一个需要 Node >= V14 的项目,并希望在 node 版本不匹配时防止 npm 脚本的执行。
通过在 .npmrc 和 package.json 中使用 engines,我可以防止 npm install 在 node 版本不匹配时运行。
然而,是否有任何方法可以防止在找不到适当的 node 版本时执行 npm start?
2个回答

4

简短回答: NPM没有提供内置功能来实现这一点。


解决方案:

然而,您可以通过利用自定义的node.js辅助脚本来满足您的要求:

  1. Save the following check-version.js script in the root of your project directory, i.e. save it at the same level where package.json resides

    check-version.js

    const MIN_VERSION = 14;
    const nodeVersion = process.version.replace(/^v/, '');
    const [ nodeMajorVersion ] = nodeVersion.split('.');
    
    if (nodeMajorVersion < MIN_VERSION) {
      console.warn(`node version ${nodeVersion} is incompatible with this module. ` +
          `Expected version >=${MIN_VERSION}`);
      process.exit(1);
    }
    
  2. In the scripts section of your package.json define your start script as follows:

    package.json

    ...
    "scripts": {
      "start": "node check-version && echo \"Running npm start\""
    },
    ....
    

    Note Replace the echo \"Running npm start\" part (above) with whatever your current start command is.


解释:

说明:

check-version.js中,我们通过process.version获取Node.js版本字符串,并使用 replace() 方法去掉前缀v注意:您可能更喜欢使用process.versions.node而不是replace来获取没有前缀v的版本字符串。 接下来,我们仅从版本字符串中获取Major版本,然后将其赋值给变量nodeMajorVersion
最后,在if语句中,我们检查nodeMajorVersion是否小于期望的最低node.js版本(MIN_VERSION)。如果小于期望的版本,我们会向用户发出警告,并使用退出代码1调用process.exit()方法。

1
取决于您的start做什么,但如果它是您的代码:
if (process.versions.node.split('.')[0] < 14) process.exit(1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接