Setting Up npm

It can be difficult with a history of older node_modules on the system to get sanity around npm installations.
Here we will purge the system of npm and nodejs and node_modules. Then we will reinstall.
This setup guide will ensure you have all node_modules and npm related stuff in your ~/.npm directory. This removes the requirement of ever having to run “sudo npm install”.

While this blog uses Debian based apt calls, you can readily replace with your OS’s package management calls.

Setting up npm

First run this script to add a new path to what will be the new npm binary directory :

export CNT=`grep npm\/bin ~/.bashrc`
if [ -z "$CNT" ]; then
echo 'export PATH=~/.npm/bin:$PATH' >> ~/.bashrc
else
echo npm path already in your bashrc file, not altering.
fi

Second get rid of packages :

sudo apt -y remove nodejs npm libnode-dev
sudo apt -y autoremove
rm -rf ~/.npm ~/.npmrc ~/.node_modules ~/.yalc

Now find then remove all node_modules from my system which aren’t part of other packages, such as atom :

sudo find / -name 'node_modules' 2> /dev/null |  grep -v emsdk-portable

helped me find all node_modules on my system. Once you find node_modules directories, delete them.

sudo rm -rf /usr/local/lib/node_modules

ok now install nodejs and npm again :

sudo apt -y install nodejs npm libnode-dev

Setup the ~/.npm directory as our default install directory. Link the global node_modules folder to where npm will look for them.

mkdir ~/.npm
echo 'prefix = ~/.npm' > ~/.npmrc
ln -s ~/.npm/lib/node_modules ~/.node_modules

NOTE: from now onwards, never call “sudo npm install” only call “npm install” as we are installing to ~/.npm

Next, we install a particular version of npm (you can change 8.2.0 to latest below to get the latest npm version) :

. ~/.bashrc
npm i -g npm@8.2.0
. ~/.bashrc

Next step is to uninstall apt’s npm :

sudo apt -y remove npm
sudo apt -y autoremove

On this system, check versions :

npm -v
nodejs --version

NOTE: At this point, ALL npm packages will be installed to ~/.npm. Any new binaries have to be linked to /usr/local/bin

NOTE: Never use “sudo npm install” again. Only use “npm install”

Yalc

We will manage local npm with yalc

npm i -g yalc

Setup npm-check-updates

This tool checks for updates to packages and optionally updates the package.json file with the latest versions.

npm install -g npm-check-updates

Use it like so to check for updates :

ncu

To perform the updates :

ncu -u

Comments