在 Ubuntu 上配置 Node.js 有多种方式,下面按推荐程度给你详细说明,适合不同使用场景。
适合:生产环境 / 需要指定 Node.js 版本
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
你也可以换成:
18.x(LTS)21.x(最新)sudo apt install -y nodejs
node -v
npm -v
适合:前端 / 后端开发、需要多版本切换
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
然后执行:
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20
node -v
npm -v
✅ 优点
sudo apt install nodejs npm
⚠️ 缺点:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g yarn pnpm
npm config set registry https://registry.npmmirror.com
| 场景 | 推荐方式 |
|---|---|
| 新手 / 学习 | nvm |
| 服务器 / 生产 | NodeSource |
| 临时测试 | apt |
如果你愿意,可以告诉我:
我可以给你最合适的一套配置方案。