Why not to use -g with npm

A lot of packages have mentioned on their documentation using `-g` flag to install the package. Below are few examples:

And you might be thinking that’s find to do because you might want to run it from any directory project directory. But actually it’s not that good of an idea. Your application should be self sustained. I would like it if I could just do

npm install; npm run start-dev

and start working without going into hassle to first sort out the version issues.

Pros of not using `-g`:

  • There is interface simplicity: npm install is all you need to install your packages.
  • There is application independence: Two apps can require different versions of things and they can both be installed on the same system without doing any silly path hacks.
  • And you have a full record of your dependencies in machine readable form.

Why -g exist? Why npm provided it?

`-g` is provided to install system-wide packages. But how do you define what a system-wide pacakage is? Why express is not a system-wide package? Answer is quite simple “all those things that you use outside of apps!”. Meh, still not quite clear, let’s look at some examples:

  • npm install -g eslint
  • npm install -g keybase
  • npm install -g manage-npm-scripts

How do you install packages like pm2 etc locally and use them?

I love npm scripts for doing a lot of tasks!!! It’s really good, you can get away with them and not using task managers.
Let’s again take example of pm2. If you were to run a server with -g you would have done something like so:


npm install -g pm2; pm2 start app.js --name=”dev”

Say you are in root of your project and now what you have to do is:

npm install — save pm2; ./node_modules/pm2/bin/pm2 start app.js --name=”dev”

But writing ./node_modules/pm2/bin/pm2 gets frustrating quite fast. What you could do is add a npm script to start and stop dev server like so, and npm does the path hack and make sure plain commands works:

scripts: {
“start-dev”: “pm2 start app.js --name=’dev’”,
“stop-dev”: “pm2 stop dev”
}

Now clone, install and run is all you have to do

git clone path-to-my-repo; npm install; npm run start-dev