141

I've started using npm for JavaScript package management recently. Although I do have a fair understanding of package management in different environments (let’s say using apt, rvm/gem, and pythonbrew/virtualenv/pip), I don't quite understand how npm fully fits in.

I would like to know more on how the "-g" flag works and why should I use it.

As in most blogs and wiki, they refer to using "-g" when installing without explaining why, and I understand that these packages are installed globally.

  • But why should I always install these packages globally?
  • What does it mean to install these packages without the "-g" flag?
  • What do I do to installed packages locally, let’s say sandboxed for different projects?
  • How can I then, make a list of npm packages used in a project and bundle it in the project if I needed it to check it in with version control (if possible at all)?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
suVasH.....
  • 1,720
  • 2
  • 12
  • 11

2 Answers2

151

-g is the global install flag, as explained in this answer. It's covered in detail in this node blog post.

The rules of thumb:

  • Install globally if the package provides command-line tools
  • Install locally if you're using the package as part of your application
  • Install globally and locally if both use-cases apply
Gaia
  • 2,872
  • 1
  • 41
  • 59
cbednarski
  • 11,718
  • 4
  • 26
  • 33
  • Thanks for your answer. Does "install globally and locally" mean I run the command `npm install -g http-server` and then run `npm install http-server` in my app directory? – JJJohn Feb 04 '22 at 14:58
5

While the accepted answer is correct, be aware that there is also npx which allows to conveniently run local tools.

For more information, see Introducing npx: an npm package runner

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fabb
  • 11,660
  • 13
  • 67
  • 111