Moving the global installation location for Node.js packages to a directory in your home folder on a MacBook can be a good way to avoid having to use sudo for npm installs. This allows you to manage global packages without needing administrative privileges. Here’s a step-by-step guide to achieve this:
Open your terminal and run the following command to create a new directory where your global npm packages will be stored:
mkdir ~/.npm-globalConfigure npm to use the new directory for global packages. This can be done by setting the prefix configuration parameter:
npm config set prefix '~/.npm-global'For your system to recognize and run the packages installed in the new directory, you need to add it to your PATH environment variable. You can add the following line to your .bash_profile, .zshrc, or equivalent file depending on which shell you use:
export PATH=~/.npm-global/bin:$PATHTo do this using a command in the terminal:
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bash_profileOr if you are using zsh (as is default in some recent versions of macOS):
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrcThen, apply the changes:
source ~/.bash_profile # or ~/.zshrc if using zshTo ensure that everything is set up correctly, try installing a package globally without sudo. For example:
npm install -g jshintIf there are no errors and the command completes successfully, then your new setup is working correctly.
If you want to verify that npm is indeed using the new directory, you can check the npm configuration:
npm config get prefix # Should return ~/.npm-globalYou can also verify that the PATH is set correctly:
echo $PATH # Should include ~/.npm-global/binBy following these steps, you can install global npm packages on your MacBook without needing to use sudo, which enhances your security and simplifies package management.