在 Ubuntu 上编译 Node.js,通常有两种方式:从源码编译 和 使用预编译版本。如果你明确想“编译”,下面重点讲从源码编译 Node.js 的完整流程(适用于 Ubuntu 20.04 / 22.04 / 24.04)。
sudo apt update
sudo apt upgrade -y
Node.js 源码编译需要以下工具:
sudo apt install -y \
build-essential \
curl \
git \
python3 \
python3-pip \
libssl-dev \
pkg-config
✅ Node.js 现在使用 Python 3,不再需要 Python 2
查看最新 LTS 版本:https://nodejs.org/dist/
cd /usr/local/src
sudo curl -LO https://nodejs.org/dist/v20.12.2/node-v20.12.2.tar.gz
sudo tar -xzf node-v20.12.2.tar.gz
cd node-v20.12.2
git clone https://github.com/nodejs/node.git
cd node
git checkout v20.x # 指定版本
./configure
常用参数:
./configure --prefix=/usr/local/nodejs
make -j$(nproc)
-j$(nproc)会使用所有 CPU 核心,加快编译
sudo make install
node -v
npm -v
如果 node 命令找不到,可能是 PATH 问题。
如果你使用了 --prefix:
echo 'export PATH=/usr/local/nodejs/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
make -j2
确认 Python 3 可用:
python3 --version
如果你只是想用 Node.js,而不需要修改源码:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
nvm install 20
nvm use 20
| 方式 | 适合人群 |
|---|---|
| 源码编译 | 研究 Node.js / 定制构建 |
| NodeSource | 生产环境 |
| nvm | 本地开发 |
如果你愿意,可以告诉我:
我可以给你最合适的一套方案。