PeerDependencies and Optional Dependencies
You'll learn how to declare plugin-style dependencies and handle optional platform-specific packages in your package.json.
What Are PeerDependencies?
PeerDependencies are packages your library expects the host application to provide, not packages you install yourself. They're essential for plugins, frameworks extensions, and tools that work alongside something else.
Think of it like a phone case manufacturer: they design cases for iPhones but don't ship an iPhone with every case. They expect you to already have the phone. Similarly, a React component library expects React to be installed by the consuming application, not bundled within itself.
{
"name": "my-react-plugin",
"peerDependencies": {
"react": "^18.0.0"
}
}
This tells users: "Install React 18+ yourself; I'll use whatever version you provide." This prevents duplicate installations and version conflicts when multiple packages need the same peer.
What Are Optional Dependencies?
OptionalDependencies are packages that enhance functionality but aren't required. If installation fails (maybe they're platform-specific), your package still works—just without that feature.
{
"name": "image-processor",
"optionalDependencies": {
"sharp-darwin-arm64": "^0.32.0"
}
}
Common for native binaries that only work on certain operating systems. Your code should detect if the optional dependency loaded successfully and gracefully degrade.
When to Use Each
Use peerDependencies when building plugins or extensions (ESLint plugins, Babel presets, UI component libraries). Use optionalDependencies for platform-specific optimizations or non-critical enhancements.
Key Takeaway: PeerDependencies delegate installation to the host application to avoid duplication, while optionalDependencies allow graceful failure for non-essential, often platform-specific packages.