Topic 25 of 55
Local vs Global Dependencies Installation
Overview
NPM allows you to install packages locally (for the current project only) or globally (available anywhere on your machine). It's a best practice to keep almost everything local to avoid version conflicts between projects.
Syntax
bash
# Local Installation (Default)
# Installed into ./node_modules and added to package.json
npm install lodash
# Global Installation (-g)
# Installed in your system's global node_modules directory
# Use ONLY for CLI tools you use everywhere, like typescript or nodemon
npm install -g nodemon
# Execute a locally installed CLI tool using 'npx'
# This downloads and runs a package temporarily without globally installing it
npx create-react-app my-appCommon Pitfalls
- Do not instruct other developers to run `npm install -g something` to run your project. Instead, add it to `devDependencies` and use an npm script or `npx`.
- Global packages might require `sudo` on Linux/Mac, which introduces security risks. Use local packages to avoid permission errors.
Real-World Example
Why global installations are dangerous for projects:
example
bash
// Project A relies on global 'express@3.0'
// Project B requires global 'express@4.0'
// You cannot run both simultaneously if installed globally!
// SOLUTION:
// Always install locally.
cd ProjectA && npm install express@3.0
cd ProjectB && npm install express@4.0
// Now both projects have their own isolated node_modules folders.