Use “npm install -g” without sudo


Getting rid of always prefixing sudo when installing a global npm package is pretty easy. Just two steps are needed.

1. Set global npm folder to your local home directory

First create the global folder in your home directory if it does not exist yet.

mkdir ~/.npm-global

Open a terminal and run the following command:

npm config set prefix '~/.npm-global'

Running this command will create a .npmrc file in your home directory containing the path of the new global npm folder.

File: .npmrc


2. Link npm binaries to the terminal

To be able to run the global packages in the commandline, it is required to tell the terminal where it should search for binarys. Therefor open ~/.bash_profile in your favorite text editor. If the file does not exist, create it with touch ~/.bash_profile
Append this line at the end of the file:
File: .bash_profile

export PATH=~/.npm-global/bin:$PATH

That’s it! You may need to restart your terminal in order to recognize the changes.
Alternatively you can run source ~/.bash_profile

Consider using Yarn instad npm as package manager. It chaches the packages and this way provides shorter install times and increases the helps against security lacks in hijacked npm packages.
Yarn – Getting Started
Global packages with Yarn

Leave a Reply

Your email address will not be published. Required fields are marked *