Mac安装Ionic Cordova后遇‘ionic: command not found’问题求助
I’ve seen this exact issue pop up for a lot of developers—you run npm install -g ionic cordova, the output confirms ionic@5.2.7 and cordova@9.0.0 are installed, but ionic throws a "command not found" error while cordova works perfectly. Let’s break down the fixes step by step:
1. Verify npm’s Global Package Path
First, let’s confirm where npm stores your global packages. Run this command in your terminal:
npm get prefix
This will return a path (common ones are /usr/local or ~/npm-global). Next, check if the ionic executable exists in the bin subdirectory of that path:
ls $(npm get prefix)/bin
Look for ionic in the output. If it’s missing, the installation likely failed silently (usually due to permissions). If it’s present, the problem is almost certainly that this bin path isn’t included in your system’s PATH environment variable.
2. Add npm’s Bin Path to Your System PATH
Run this to see what’s currently in your PATH:
echo $PATH
Compare the output to the $(npm get prefix)/bin path from step 1. If it’s not listed, we’ll add it to your shell config:
For Bash users:
Edit your ~/.bash_profile file (create it if it doesn’t exist) and add this line:
export PATH="$PATH:$(npm get prefix)/bin"
Save the file, then reload the config with:
source ~/.bash_profile
For Zsh users (default on newer macOS):
Edit your ~/.zshrc file and add the same line as above, then reload with:
source ~/.zshrc
Now try running ionic --version—it should work if this was the root cause.
3. Fix Permissions (If Ionic Executable Is Missing)
If the ionic file wasn’t in the bin directory, permissions are the likely culprit. Avoid using sudo for npm installs long-term, so let’s fix npm’s global directory ownership first:
sudo chown -R $USER:$(id -g -n $USER) $(npm get prefix)/{lib/node_modules,bin,share}
Then uninstall and reinstall Ionic:
npm uninstall -g ionic npm install -g ionic
4. Check for Node Version Manager (nvm) Conflicts
If you use nvm to manage multiple Node.js versions, you might have installed Ionic under one version but are running a different one in your terminal. Run:
nvm current
Make sure this matches the Node version you used to install Ionic. If not, switch to that version with nvm use <version> and reinstall Ionic, or install it under your current active version.
内容的提问来源于stack exchange,提问作者Arno

