解决 nvm 无法锁定node版本的问题

14 min read

.nvmrc

在项目根目录添加 .nvmrc 文件可指定 nvm 默认的 node 版本。

$ node -v > .nvmrc

在执行 nvm use, nvm install, nvm exec, nvm runnvm which 这些命令时,都会从该文件读取版本信息。

在新的环境下,clone 项目后通过 nvm install && nvm use 就可使用上与项目相匹配的 node 版本。

engines

通过在 package.json 中指定 engines 字段,可限定项目使用的 node 版本,甚至 npm 版本。

不过,通常情况下,配置之后你会发现,该字段只对 yarn 生效:

$ yarn
yarn install v1.22.5
info No lockfile found.
[1/5]   Validating package.json...
error test-node@1.0.0: The engine "node" is incompatible with this module. Expected version ">=14". Got "10.22.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

而使用 npm 进行安装时,直接成功没有提示,连 warnning 都没有:

$ npm i
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

up to date in 0.48s
found 0 vulnerabilities

根据 npm 文档中关于 engines 的部分,发现要让 npm 识别 engines 字段,还需要配置 engine-strict: true,但是进一步看,

This feature was removed in npm 3.0.0

王德发?

好消息是,进一步研究发现,创建 .npmrc 文件配置如下内容:

engine-strict = true

就可以使得 engines 字段对 npm 生效了。

$ npm i
npm ERR! code ENOTSUP
npm ERR! notsup Unsupported engine for [email protected]: wanted: {"node":">=14"} (current: {"node":"10.22.0","npm":"6.14.6"})
npm ERR! notsup Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Not compatible with your version of node/npm: [email protected]
npm ERR! notsup Required: {"node":">=14"}
npm ERR! notsup Actual:   {"npm":"6.14.6","node":"10.22.0"}

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wayongliu/.npm/_logs/2020-09-14T13_43_33_020Z-debug.log