一些老項目對 node 版本是有要求的,往往使用默認的新版本包安裝不上,scripts 也跑不起來。
之前就遇到過運行一個小程序項目時,根據文檔來,第一步安裝就出錯。本着辦法總比問題多的理念,來一個解決一個。問題還真是一個接一個的出現。折騰頭天,在解決一個包的運行問題時,發現切換到較低版本的 node 后一切安好。
所以,對於老項目,最好使用兼容性強的版本 8 或 10 的 LTS。
解決問題的根本方法是項目中要對 node 版本進行提示或鎖死,否則新人仍會踩坑。
.nvmrc
在項目根目錄添加 .nvmrc 文件可指定 nvm 默認的 node 版本。
$ node -v > .nvmrc
在執行 nvm use
, nvm install
, nvm exec
, nvm run
或 nvm 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 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.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: