Ubuntu中如何恢复npm默认全局路径?全局包失效问题修复
Hey there, let's work through these two issues one by one. I’ve dealt with similar path-related headaches in npm before, so I’ll walk you through the fixes clearly.
First, let’s check where npm is currently pointing for global packages. Run this command in your terminal:
npm config get prefix
By default, on a system-wide Node.js installation (via apt or official binaries), this should return /usr/local. If it shows something else (like a custom directory you set earlier), we’ll reset it.
Steps to reset:
- Clear the custom prefix: Run this to remove any manually set prefix and revert to npm’s default:
Alternatively, you can explicitly set it back to the system default:npm config delete prefixnpm config set prefix /usr/local - Clean up your shell config: If you added a custom path to your
~/.bashrc,~/.zshrc, or similar shell profile file (likeexport PATH="$HOME/my-custom-npm-dir/bin:$PATH"), open that file and delete that line. Then reload the profile to apply changes:source ~/.bashrc # For Bash users # OR source ~/.zshrc # For Zsh users - Check your
.npmrcfile: If you have a~/.npmrcfile in your home directory, open it and remove any line that starts withprefix=. This ensures no leftover config overrides the default.
Verify the fix:
Install a test package globally and see if it works:
npm install -g cowsay cowsay "Hello again, default paths!"
If you see the cow saying that message, you’re good to go.
Chances are, when you modified node-sass’s global path, you accidentally changed npm’s global prefix setting (which affects all packages) instead of targeting just node-sass. Let’s fix that:
Steps to resolve:
- Ensure npm’s prefix is correct: Follow the steps in section 1 to make sure npm is using the default
/usr/localprefix. This is the most common culprit here. - Check your system PATH: Make sure npm’s global
bindirectory (default:/usr/local/bin) is in your system’s PATH. Run this to check:
Ifecho $PATH/usr/local/binisn’t listed, add it to your shell profile file (e.g.,~/.bashrc):echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc - Target node-sass specifically (if needed): If you still need a custom path for node-sass’s binary files (instead of changing npm’s global prefix), use node-sass’s dedicated config setting instead. For example:
This way, only node-sass uses that custom path, and other global packages remain unaffected.npm config set sass_binary_path ~/.node-sass/bin/node-sass - Reinstall problematic packages: Any packages you installed while the prefix was wrong might be in the wrong directory. Uninstall and reinstall them:
Replacenpm uninstall -g <package-name> npm install -g <package-name><package-name>with the package that’s not working (likevue-cli,webpack-cli, etc.).
Verify the fix:
Run the command for the problematic package—for example, if it’s webpack, run:
webpack --version
If it outputs the version number, you’ve fixed the issue.
内容的提问来源于stack exchange,提问作者Fruity Pie

