Ubuntu为何应避免用apt-get安装Node.js?替代方案及相关疑问(含React)
apt-get on Ubuntu Great question! Let’s break this down clearly:
Ubuntu’s default software repositories ship with severely outdated Node.js versions—we’re talking releases that are 2-3 years behind current stable builds. This leads to compatibility issues with modern npm packages, frameworks like React, and even core Node.js features.
The bigger pain point, though, is permission errors when installing global npm modules. When you use apt-get to install Node.js, npm’s default global module directory is a system-level path (usually /usr/lib/node_modules). As a regular user, you don’t have write access here. If you force the install with sudo, you’ll mess up file ownership (setting it to root), which causes endless headaches later—like being unable to update packages or run tools without elevated privileges.
Global npm modules are tools you need to use from any directory in your terminal. For example:
create-react-app(to quickly bootstrap React projects)webpack-cli(for bundling frontend code)eslint(for automated code linting)
Installing these globally lets you call them by name directly, instead of navigating to their installation folder or typing long relative paths every time. It’s a massive productivity boost for daily development.
curl Fixes This The NodeSource PPA (Personal Package Archive) solves both the version and permission problems out of the box. Here’s what each command does:
curl -sL https://deb.nodesource.com/setup_10.x | sudo bash: This script adds the NodeSource repository (for Node.js 10.x) to your system’s package sources, updates the package cache, and configures required dependencies. The-sLflag keepscurlsilent and follows redirects for a clean setup.sudo apt install nodejs: Installs the latest stable Node.js 10.x release from the new PPA, along with a matching version of npm. Critically, this setup configures npm’s global module directory to a user-owned path (typically~/.npm-global), so you can install global modules withoutsudoand avoid permission messes.npm -v: Verifies that npm installed correctly and shows you its version number.
Once you’ve set up Node.js via the PPA, getting React running is straightforward:
- Install the
create-react-apptool globally (this only needs to be done once):npm install -g create-react-app - Create a new React project (replace
my-react-appwith your preferred project name):create-react-app my-react-app - Navigate into your project directory:
cd my-react-app - Start the development server—this will open your React app in your default browser and auto-reload when you make code changes:
npm start
内容的提问来源于stack exchange,提问作者Smriti Mittal

