确保你的项目在所有环境中使用相同的Node.js版本是一个好主意。 这样你就可以确保你的代码从开发到生产都能按预期工作。
npm有一个内置的功能,可以检查正在运行的Node.js版本是否符合预期,如果不符合就会失败。 要完全配置这个功能需要两个设置。
首先, engines 在package.json 的设置中声明你支持的Node.js版本。
{
"name": "example",
"private": true,
"engines": {
"node": "16.x"
}
}
16.x 通常这就足够了,因为在大多数环境中,你可能会安装一系列的最新版本,以获得所有的错误修复。
第二,在你的package.json 与旁边添加一个.npmrc 文件。
engine-strict=true
engine-strict 设置告诉npm在不支持的版本上以错误方式停止。 这看起来像
$ npm install
npm ERR! code EBADENGINE
npm ERR! engine Unsupported engine
npm ERR! engine Not compatible with your version of node/npm: example@1.0.0
npm ERR! notsup Not compatible with your version of node/npm: example@1.0.0
npm ERR! notsup Required: {"node":"16.x"}
npm ERR! notsup Actual: {"npm":"7.7.6","node":"v15.14.0"}
npm ERR! A complete log of this run can be found in:
npm ERR! /.../.npm/_logs/2022-03-25T11_45_49_682Z-debug.log
没有engine-strict,npm会记录一个警告,但继续进行。
$ npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: 'example@1.0.0',
npm WARN EBADENGINE required: { node: '16.x' },
npm WARN EBADENGINE current: { node: 'v15.14.0', npm: '7.7.6' }
npm WARN EBADENGINE }
up to date in 1s
70 packages are looking for funding
run `npm fund` for details
这样的警告很容易被忽略,特别是当npm 被CI工具等自动调用的时候。所以,最好使用 engine-strict.