When should i use npm with "-g" flag and why?

Npm

Npm Problem Overview


I've started using npm for js package management recently. Although I do have a fair understanding of package management in different enivronments(lets say using apt, rvm/gem, 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 use "-g" when installing without explaining why, and I understand that these packages are installed globally.

  • But why should I install these packages always globally ?
  • What does it mean to install these packages without the "-g" flag ?
  • What do I do to installed packages locally, lets 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) ?

Npm Solutions


Solution 1 - Npm

-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

Solution 2 - Npm

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

For more information, see https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsuVasH.....View Question on Stackoverflow
Solution 1 - NpmcbednarskiView Answer on Stackoverflow
Solution 2 - NpmfabbView Answer on Stackoverflow