Skip to content

Instantly share code, notes, and snippets.

@dcfrancisco
Last active April 12, 2024 11:33
Show Gist options
  • Save dcfrancisco/f45d9d9adccce6276a11fc36d3f7b43f to your computer and use it in GitHub Desktop.
Save dcfrancisco/f45d9d9adccce6276a11fc36d3f7b43f to your computer and use it in GitHub Desktop.

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:

1. Create a New Directory for Global Packages

Open your terminal and run the following command to create a new directory where your global npm packages will be stored:

mkdir ~/.npm-global

2. Configure npm to Use the New Directory

Configure 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'

3. Update Your PATH

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:$PATH

To do this using a command in the terminal:

echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bash_profile

Or if you are using zsh (as is default in some recent versions of macOS):

echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc

Then, apply the changes:

source ~/.bash_profile  # or ~/.zshrc if using zsh

4. Test Your Setup

To ensure that everything is set up correctly, try installing a package globally without sudo. For example:

npm install -g jshint

If there are no errors and the command completes successfully, then your new setup is working correctly.

5. Optionally, Check npm Variables

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-global

You can also verify that the PATH is set correctly:

echo $PATH  # Should include ~/.npm-global/bin

By 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment