Difference Between npm Global and Local Install
When working with Node.js, understanding how to manage package dependencies is crucial for maintaining a clean and efficient development environment. This article explains the key differences between global and local npm installations, detailing where packages are stored, how they are accessed, and when to use each method to optimize your workflow.
Local Installation
A local installation is the default behavior when you run the
npm install command. It is designed to manage dependencies
for a specific project.
- Storage Location: Packages are installed inside the
node_modulesdirectory of the project where the command is run. They are also added to the project’spackage.jsonfile underdependenciesordevDependencies. - Access: These packages can only be imported and
used within that specific project via
require()orimportstatements. They are not accessible globally from the command line unless run via an npm script ornpx. - Best Used For: Frameworks, libraries, and utilities that your project’s code directly relies on to run (e.g., React, Express, Lodash, or Jest).
- Command:
npm install <package-name>
Global Installation
A global installation makes a package available system-wide, allowing you to run its commands directly from your terminal regardless of your current directory.
- Storage Location: Packages are stored in a single,
centralized system directory (such as
/usr/local/lib/node_moduleson macOS/Linux or%AppData%\npm\node_moduleson Windows). They are not added to any project’spackage.jsonfile. - Access: The executable binaries of these packages
are added to your system’s PATH, making them executable from any
command-line interface (CLI) window. They cannot be easily imported into
your local project files using
require()orimport. - Best Used For: CLI tools, generators, and
development utilities that you use across multiple projects (e.g.,
nodemon,aws-cli, ortypescript). - Command:
npm install -g <package-name>
Key Differences Summary
| Feature | Local Installation | Global Installation |
|---|---|---|
| Command | npm install <package-name> |
npm install -g <package-name> |
| Storage Location | Project-specific
node_modules/ folder |
System-wide node directory |
| Project Dependency | Listed in package.json |
Not listed in
package.json |
| Usage | Imported into project code
(require/import) |
Run as commands in the terminal |
| Scope | Restricted to the project directory | Accessible across the entire system |
| Version Control | Locked per project, ensuring consistency | Shares one version across all projects |
A Modern Alternative: npx
For CLI tools that you only need to run occasionally, you can avoid
global installations entirely by using npx. Running
npx <package-name> downloads and executes the tool
temporarily without permanently installing it globally on your system.
This ensures you always use the latest version and keeps your global
space clutter-free.