Ubuntu 系统(包括 WSL 中的 Ubuntu)安装 Node.js、npm 和 Yarn

Ubuntu 系统(包括 WSL 中的 Ubuntu)安装 Node.js、npm 和 Yarn

以下是在 Ubuntu 系统(包括 WSL 中的 Ubuntu)安装 Node.jsnpmYarn 的完整步骤,涵盖多种安装方式及常见问题解决方案:


一、安装 Node.js 和 npm

方法 1:通过 NodeSource 安装(推荐,版本新)
    • 如果需要其他版本(如 18.x),替换链接中的 20.x

验证安装

node -v # 应输出 v20.x.xnpm -v # 应输出对应版本

安装 Node.js 和 npm

sudoaptinstall -y nodejs 

添加 NodeSource 仓库(以 Node.js 20.x 为例):

curl -fsSL https://deb.nodesource.com/setup_20.x |sudo -E bash - 

方法 2:使用 nvm(灵活管理多版本)

验证安装

node -v npm -v 

安装指定版本的 Node.js(自动包含 npm):

nvm install --lts # 安装最新 LTS 版本# 或指定版本 nvm install20.5.0 

安装完成后,重启终端或运行:

source ~/.bashrc 

安装 nvm(Node Version Manager)

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

方法 3:通过 Ubuntu 官方仓库(版本较旧,不推荐)
sudoapt update sudoaptinstall nodejs npm

二、安装 Yarn

方法 1:通过 npm 安装(推荐)

验证安装

yarn --version 

全局安装 Yarn

npminstall -g yarn

方法 2:通过 Yarn 官方仓库

安装 Yarn

sudoapt update sudoaptinstallyarn

添加 GPG 密钥和仓库

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg |sudo apt-key add - echo"deb https://dl.yarnpkg.com/debian/ stable main"|sudotee /etc/apt/sources.list.d/yarn.list 

三、配置镜像源(加速下载)

1. 配置 npm 镜像源
npm config set registry https://registry.npmmirror.com 
2. 配置 Yarn 镜像源
yarn config set registry https://registry.npmmirror.com 

四、解决全局安装权限问题

如果安装全局包时出现 EACCES 权限错误,按以下步骤修复:

将路径添加到环境变量

echo'export PATH=~/.npm-global/bin:$PATH'>> ~/.bashrc source ~/.bashrc 

配置 npm 全局安装目录

mkdir ~/.npm-global npm config set prefix ~/.npm-global 

五、常见问题解决

1. 安装后命令未找到(如 nodeyarn
  • 原因:环境变量未生效。

解决

source ~/.bashrc # 重新加载配置echo$PATH# 检查路径是否包含正确目录
2. 版本冲突

如果通过 aptnvm 同时安装了 Node.js,优先使用 nvm 版本:

nvm use --lts # 切换到 nvm 管理的版本
3. 彻底卸载重装
  • 重新按上述步骤安装。

卸载 Node.js 和 npm

sudoapt purge --auto-remove nodejs npmrm -rf ~/.npm ~/.nvm 

六、验证环境

node -v # 输出 Node.js 版本npm -v # 输出 npm 版本yarn -v # 输出 Yarn 版本

附:完整流程示例(推荐使用 nvm)

# 1. 安装 nvmcurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh |bashsource ~/.bashrc # 2. 安装 Node.js 和 npm nvm install --lts # 3. 安装 Yarnnpminstall -g yarn# 4. 配置镜像源npm config set registry https://registry.npmmirror.com yarn config set registry https://registry.npmmirror.com 

如有其他问题,请提供以下信息:

  1. 终端执行命令的具体报错内容。
  2. 运行 node -vnpm -vyarn -v 的输出结果。
Could not load content