likes
comments
collection
share

Node.js版本管理

作者站长头像
站长
· 阅读数 27
最近运行一个前端项目时,出现了Node.js版本与依赖版本不符的问题,如下:
error @typescript-eslint/eslint-plugin@5.21.0: The engine "node" is incompatible with this module. Expected version "^12.22.0 || ^14.17.0 || >=16.0.0". Got "14.16.0"
error Found incompatible module.

正如上面的错误提示,本地安装的node版本是14.16.0,于是打算将版本升级到大于16.0.0的版本。

这里介绍一个node版本管理工具,可以方便的管理你本地的版本。

安装命令:

npm i n -g

如果出现了下面的错误,你需要加上 sudo npm i n -g

➜  quick-demo-vue3-ts git:(main) npm i n -g
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules'
npm ERR! }

安装完成后,可以使用下面的命令查看使用方法:

n --help

Usage: n [options] [COMMAND] [args]

Commands:

  n                              Display downloaded Node.js versions and install selection
  n latest                       Install the latest Node.js release (downloading if necessary)
  n lts                          Install the latest LTS Node.js release (downloading if necessary)
  n <version>                    Install Node.js <version> (downloading if necessary)
  n install <version>            Install Node.js <version> (downloading if necessary)
  n run <version> [args ...]     Execute downloaded Node.js <version> with [args ...]
  n which <version>              Output path for downloaded node <version>
  n exec <vers> <cmd> [args...]  Execute command with modified PATH, so downloaded node <version> and npm first
  n rm <version ...>             Remove the given downloaded version(s)
  n prune                        Remove all downloaded versions except the installed version
  n --latest                     Output the latest Node.js version available
  n --lts                        Output the latest LTS Node.js version available
  n ls                           Output downloaded versions
  n ls-remote [version]          Output matching versions available for download
  n uninstall                    Remove the installed Node.js

只要输入n lts就可以自动安装稳定版本的node.js了。

sudo n lts
  installing : node-v16.16.0
       mkdir : /usr/local/n/versions/node/16.16.0
       fetch : https://nodejs.org/dist/v16.16.0/node-v16.16.0-darwin-arm64.tar.xz
     copying : node/16.16.0
   installed : v16.16.0 (with npm 8.11.0)

node -v
v16.16.0

这样你就可以安装多个版本的node.js:

    node/14.17.2
  ο node/16.16.0

因为有一些npm package是在高版本的node无法使用的,如fiber。这是你只需切换到低版本就可以了。

除了 n,还有别的 nvm 比较适合在Linux系统上使用,大家可以点击链接去查看,这里不在赘述。

文章首发于我的博客 《IICOOM技术博客-Node.js版本管理》