In a package.json
file for npm, dependencies are categorized into three main types to manage their roles in development, production, and compatibility:
1. dependencies
- Purpose: Packages required for your application to run in production.
- When Installed: Automatically installed when someone runs
npm install your-package
. - Example: Libraries like
express
,react
, orlodash
that your code directly uses. - How to Add:
bash npm install package-name
2. devDependencies
- Purpose: Packages needed only during development (e.g., testing, bundling, linting).
- When Installed: Not installed when your package is added as a dependency. Only installed if someone clones your repo and runs
npm install
. - Example: Tools like
jest
,webpack
,eslint
, ortypescript
. - How to Add:
bash npm install package-name --save-dev
3. peerDependencies
- Purpose: Packages your package expects the host project to provide. Used to avoid version conflicts when your package acts as a plugin/library.
- When Installed: Not installed automatically by default (prior to npm 7). The host project must explicitly include them.
- Example: A React plugin listing
react
as a peerDependency to ensure compatibility with the host’s React version. - How to Add: Manually add to
peerDependencies
inpackage.json
:json { "peerDependencies": { "react": ">=16.8.0" } }
Key Differences
Type | Installed When? | Use Case | Example |
---|---|---|---|
dependencies | Always (production) | Core functionality | express , react |
devDependencies | Only during development | Build/test tools | jest , webpack |
peerDependencies | Host project must provide | Plugins, libraries, version alignment | react (for a component) |
Practical Example
Scenario: You’re building a React component library.
dependencies
: None (your library doesn’t bundle React).peerDependencies
:"react": "^18.0.0"
(users must install React themselves).devDependencies
:@types/react
,jest
,webpack
(for testing/building).
Behavior by npm Versions
- npm < 7: Peer dependencies are not auto-installed. Users see warnings if missing.
- npm ≥ 7: Peer dependencies are auto-installed by default, but conflicts may cause errors.
Why This Matters
- Reduced Bloat: Avoid installing unnecessary packages in production (via
devDependencies
). - Version Safety: Prevent duplicate/conflicting versions of critical libraries (via
peerDependencies
). - Clear Contracts: Declare exactly what your package needs to function.
Use dependencies
for runtime needs, devDependencies
for tooling, and peerDependencies
to signal compatibility requirements.