When is it appropriate to use the '-g' flag with npm and why is it important?

I’ve recently started using npm for managing JavaScript packages, and while I understand package management from other systems like apt, rvm/gem, and pythonbrew/virtualenv/pip, I’m unclear on npm’s specifics.

I want to understand how the ‘-g’ flag operates and the reasons for utilizing it. Often, I find references about using ‘-g’ for installations, but with little explanation about the implications. I know it installs packages globally, but several questions linger:

  • Why is it necessary to always install certain packages with a global flag?
  • What does it mean to install packages without using the ‘-g’ option?
  • How can I handle packages locally, perhaps in a setup for specific projects?
  • Is there a method to compile a list of npm packages utilized in a project for version control purposes?

I’m hoping to get clear advice on how to effectively install npm packages and manage project dependencies.

The ‘-g’ flag changes the installation location of npm packages. When used, packages are installed in a global directory, allowing access from anywhere in your terminal, which is useful for command-line tools like create-react-app or nodemon. Conversely, omitting the ‘-g’ flag installs packages locally within a project’s node_modules folder, restricting their usage to that specific project. This is crucial for maintaining project-specific dependencies and avoiding version conflicts. Always utilize package.json to track local dependencies, ensuring consistent project setups.