What's the difference between global and local npm installation and when to use each?

I’m pretty new to npm and JavaScript development. I keep seeing tutorials where people use npm install -g for some packages but just npm install for others. I get that the -g means global but I’m confused about when I should actually use it.

My main questions are:

  • When is it better to install packages globally vs locally?
  • What happens when I don’t use the -g flag?
  • How do I keep different projects separate with their own dependencies?
  • Is there a way to track which packages my project uses so other developers can install the same ones?

I come from using other package managers like pip and gem, but npm seems to work differently and I want to make sure I’m doing things the right way.

It’s all about scope and how you use them. Local installations dump packages into your project’s node_modules folder - only that project can touch them. Use this for dependencies like React, Express, or anything your code actually imports. Global installations go system-wide so you can run them from anywhere via command line. I made this mistake early on - installed everything globally and got hit with version conflicts between projects. Now I only go global for CLI tools I need everywhere, like nodemon or webpack-cli. Everything else stays local to keep projects separate and avoid those ‘works on my machine’ headaches. Your package.json automatically tracks local dependencies when you use npm install --save, so other devs just run npm install and get the exact same versions.

Global packages serve as system utilities, allowing you to run them from any terminal location. In contrast, local packages are confined to your project’s node_modules folder, strictly functioning within that project. I typically opt for global installs for development tools that I require across multiple projects, such as TypeScript compiler or Jest, while using local installations for project-specific dependencies your code imports. This is crucial, as updating a global package might inadvertently disrupt multiple projects. When installing locally, npm conveniently updates your package.json file, ensuring that other developers can replicate your environment by running npm install.

global installs are handy for tools you need in various projects, like create-react-app. local installs are confined to your project folder. if you don’t use -g, it goes into node_modules in that folder. package.json helps keep the same version for everyone.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.