【Node.js】 使用 nvm 管理本地 Node.js 版本

Posted by 西维蜀黍 on 2019-10-19, Last Modified on 2022-12-10

Background

在我们的日常开发中经常会遇到这种情况:手上有好几个项目,每个项目的需求不同,进而不同项目必须依赖不同版的 NodeJS 运行环境。如果没有一个合适的工具,这个问题将非常棘手。

nvm 应运而生,nvm 是 Mac 下的 node 管理工具,有点类似管理 Ruby 的 rvm,如果需要管理 Windows 下的 node,官方推荐使用 nvmwnvm-windows。不过,nvm-windows 并不是 nvm 的简单移植,他们也没有任何关系。但下面介绍的所有命令,都可以在 nvm-windows 中运行。

Install nvm

To install or update nvm, you can use the install script using cURL:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.0/install.sh | bash

or Wget:

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.0/install.sh | bash

Verify installation

To verify that nvm has been installed, do:

command -v nvm

which should output nvm if the installation was successful. Please note that which nvm will not work, since nvm is a sourced shell function, not an executable binary.

Usage

Install node

To download, compile, and install the latest release of node, do this:

nvm install node # "node" is an alias for the latest version

To install a specific version of node:

nvm install 6.14.4 # or 10.10.0, 8.9.1, etc

The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).

List all node versions

$ nvm ls
         nvm
     v0.8.26
    v0.10.26
    v0.11.11
->  v4.3.2

Use a specific node version

In any new shell just use the installed version:

nvm use node

Or you can just run it:

nvm run node --version

Alias for a specific node version

我们还可以用 nvm 给不同的版本号设置别名:

nvm alias awesome-version 4.2.2

我们给 4.2.2 这个版本号起了一个名字叫做 awesome-version,然后我们可以运行:

nvm use awesome-version

下面这个命令可以取消别名:

nvm unalias awesome-version

另外,你还可以设置 default 这个特殊别名:

nvm alias default node

在项目中使用不同版本的 Node

我们可以通过创建项目目录中的 .nvmrc 文件来指定要使用的 Node 版本。之后在项目目录中执行 nvm use 即可。.nvmrc 文件内容只需要遵守上文提到的语义化版本规则即可。另外还有个工具叫做 avn,可以自动化这个过程。

在多环境中,npm该如何使用呢?

每个版本的 Node 都会自带一个不同版本的 npm,可以用 npm -v 来查看 npm 的版本。全局安装的 npm 包并不会在不同的 Node 环境中共享,因为这会引起兼容问题。它们被放在了不同版本的目录下,例如 ~/.nvm/versions/node//lib/node_modules 这样的目录。这刚好也省去我们在 Linux 中使用 sudo 的功夫了。因为这是用户的主文件夹,并不会引起权限问题。

但问题来了,我们安装过的 npm 包,都要重新再装一次?幸运的是,我们有个办法来解决我们的问题,运行下面这个命令,可以从特定版本导入到我们将要安装的新版本 Node:

nvm install v5.0.0 --reinstall-packages-from=4.2

Reference