如何让全局安装的Node.js模块(如create-react-app)在终端运行?
Hey there! I’ve run into this exact issue a few times, so let’s work through it together. The core problem here is almost always related to your system’s PATH environment variable not including Yarn’s global binary directory, or a minor installation glitch. Here’s how to fix it:
Step 1: Find Yarn’s Global Bin Directory
First, let’s confirm where Yarn stores global packages. Run this command in your terminal:
yarn global bin
This will output a path (e.g., ~/.yarn/bin on macOS/Linux, C:\Users\YourName\AppData\Local\Yarn\bin on Windows). This is the directory your system needs to recognize to run create-react-app.
Step 2: Add the Directory to Your System PATH
If the path from Step 1 isn’t listed in your system’s PATH, your terminal can’t find the create-react-app command. Here’s how to add it:
For macOS/Linux:
- Open your shell config file (e.g.,
~/.zshrcfor Zsh,~/.bashrcfor Bash) in a text editor. - Add this line at the bottom:
export PATH="$PATH:$(yarn global bin)" - Save the file and reload the config with:
source ~/.zshrc # Or source ~/.bashrc if using Bash
For Windows:
- Open System Properties → go to the Advanced tab → click Environment Variables.
- Under "User Variables" or "System Variables", find the
PATHvariable and click Edit. - Click New and paste the path you got from
yarn global bin. - Click OK to save all changes, then restart your terminal.
Step 3: Fix Installation Glitches (If PATH Is Correct)
If your PATH is set up right but the command still fails, try forcing a reinstall to fix corrupted or incomplete files:
yarn global add create-react-app --force
Alternative: Use npx (No Global Install Needed)
If you want to skip global install headaches entirely, the official React docs now recommend using npx to create projects directly. This pulls the latest version of create-react-app temporarily, so you don’t have to worry about global setup:
npx create-react-app my-react-project
Just replace my-react-project with your preferred project name, and it’ll handle the rest automatically.
Bonus: Check for Conflicting Installations
If you previously installed create-react-app via npm, it might conflict with Yarn’s version. Uninstall both to start fresh:
yarn global remove create-react-app npm uninstall -g create-react-app
Then use either the fixed global Yarn install or the npx method to create your project.
内容的提问来源于stack exchange,提问作者David Essien

