前言

目前常见的 Node.js 版本管理工具有 nvm、n、nvs、fnm 和 Volta。

各自的特点参考以下文章:

介绍

详细内容参考:官方文档

Volta 的任务是管理你的 JavaScript 命令行工具,例如 node 、 npm 、 yarn ,或作为 JavaScript 包一部分分发的可执行文件。

特点:

  • 速度快
  • 跨平台支持
  • 可以无缝切换版本

安装

Unix

在大多数 Unix 系统(包括 macOS)上,可以使用一条命令安装 Volta:

1
curl https://get.volta.sh | bash

对于 bash、zsh 和 fish,安装程序将自动更新控制台启动脚本,如果希望阻止对控制台启动脚本的修改,执行以下命令安装:

1
curl https://get.volta.sh | bash -s -- --skip-setup

Windows

方法一:使用 winget 安装:

1
winget install Volta.Volta

方法二:通过下载安装程序并手动运行来安装

指定默认版本

安装完成后,需要指定默认的 node 版本

特定版本:如果不指定精确版本,会自动选择合适的版本

1
volta install node@22.5.1

最新 LTS 版本:

1
volta install node

Volta 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
The JavaScript Launcher ⚡

To install a tool in your toolchain, use `volta install`.
To pin your project's runtime or package manager, use `volta pin`.

USAGE:
volta [FLAGS] [SUBCOMMAND]

FLAGS:
--verbose
Enables verbose diagnostics

--quiet
Prevents unnecessary output

-v, --version
Prints the current version of Volta

-h, --help
Prints help information

SUBCOMMANDS:
fetch Fetches a tool to the local machine
install Installs a tool in your toolchain
uninstall Uninstalls a tool from your toolchain
pin Pins your project's runtime or package manager
list Displays the current toolchain
completions Generates Volta completions
which Locates the actual binary that will be called by Volta
setup Enables Volta for the current user / shell
help Prints this message or the help of the given subcommand(s)

项目实践

使用 volta pin 命令可以自动为项目固定 node 等版本

例如,在项目根目录执行:

1
2
volta pin node@16
volta pin npm@8

会在 package.json 中自动写入:

1
2
3
4
"volta": {
"node": "16.20.2",
"npm": "8.19.4"
}

如果用户安装了 Volta,会在进入该项目时,自动切换对应的 node 版本