您的位置:首页 > Web前端 > Node.js

锁定项目的 node 版本

2021-05-01 13:50 916 查看

一些老项目对 node 版本是有要求的,往往使用默认的新版本包安装不上,scripts 也跑不起来。

之前就遇到过运行一个小程序项目时,根据文档来,第一步安装就出错。本着办法总比问题多的理念,来一个解决一个。问题还真是一个接一个的出现。折腾头天,在解决一个包的运行问题时,发现切换到较低版本的 node 后一切安好。

所以,对于老项目,最好使用兼容性强的版本 8 或 10 的 LTS。

解决问题的根本方法是项目中要对 node 版本进行提示或锁死,否则新人仍会踩坑。

.nvmrc

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

$ node -v > .nvmrc

在执行

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

在新的环境下,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 test-node@1.0.0 No description
npm WARN test-node@1.0.0 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 test-node@1.0.0: wanted: {"node":">=14"} (current: {"node":"10.22.0","npm":"6.14.6"})
npm ERR! notsup Not compatible with your version of node/npm: test-node@1.0.0
npm ERR! notsup Not compatible with your version of node/npm: test-node@1.0
564
.0
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

结合之前关于项目中私有 npm 源的设置,所以在项目中添加

.npmrc
真的是最佳实践了。

相关资源

The text was updated successfully, but these errors were encountered:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: