To remove the need for sudo when running npm commands on macOS, you can change the ownership of the npm directories to the current user. This way, you won't need to use sudo for installing global packages. Here's how you can do it:
-
Open your terminal.
-
Change the ownership of the global
node_modulesdirectory to your user. ReplaceYOUR_USERNAMEwith your actual username.
sudo chown -R $(whoami) /usr/local/lib/node_modules
- Change the ownership of the
npmcache directory as well.
sudo chown -R $(whoami) ~/.npm
- If you have
npxinstalled, you might also need to change the ownership of thenpxcache directory.
sudo chown -R $(whoami) ~/.npx
- Optionally, if you have installed Node.js via Homebrew, you might need to change the ownership of the Homebrew's Cellar node directory.
sudo chown -R $(whoami) /usr/local/Cellar/node
- Lastly, change the ownership of the
npmandnpxbinaries.
sudo chown -R $(whoami) /usr/local/bin/npm
sudo chown -R $(whoami) /usr/local/bin/npx
After performing these steps, you should be able to run npm commands without needing to prefix them with sudo.
Note: Be cautious when using sudo and chown commands, as they can affect system files and permissions. If you're not sure about your actions, it's always a good idea to seek help from someone who has more experience with Unix-based systems.
Alternative Solution:
Another approach is to configure npm to use a directory within your home directory for global installations. This way, you won't need to change any system-wide permissions.
- Make a directory for global installations:
mkdir "${HOME}/.npm-global"
- Configure npm to use the new directory:
npm config set prefix "${HOME}/.npm-global"
- Open or create a
~/.bash_profileor~/.zshrcfile and add the following line to it:
export PATH="${HOME}/.npm-global/bin:$PATH"
- Back on the command line, update your system variables:
source ~/.bash_profile
# Or if you're using zsh
source ~/.zshrc
Now, npm will install global packages in your home directory, and you won't need to use sudo for npm commands. Remember to restart your terminal or re-source your profile to ensure the changes take effect.