You are viewing...

When to use NPM's Peer Dependencies

Updated on September 21, 2020 at the 10th hour
Posted under:

DISCLAIMER: Expressed views on this blog are my own.

I'll keep it short. First tech related post in a while too.

I never used peer dependencies because I did not understand the point. It never installed the library I wanted! So it made no sense to me.

I kept running into a problem with certain libraries that require use of a singleton instance that caches data. When multiple dependencies use the same library then they will all have their own version of the library which obviously causes unforeseen issues.

There are libraries out there like Class Transformer that need only a single instance of the library. Log4Js is another one. Class Tranformer uses a singleton metadata store to store typescript reflection information. If there are two instances where the application created an instance and a dependency has its' own instance then the dependency will never see the reflection information! Same with log4js where it will not have the correct configuration for dependencies that try to log.

I was very curious about removing the duplicate dependency of that child dependency manually in node_modules, so I did it and ran the application and viola it worked! Obvious use for peer dependencies!

and that's the story of when to use NPM Peer Dependencies.


Interesting bit is that you can install the peer dependency as a dev dependency in order to use it locally (compile with typescript for me). You can use `yarn -P -D <packages>` I had no idea one could do that since it complained when I wanted to install as a dependency.


err.. It is `yarn add -P <packages>` then `yarn add -D <packages>` There is an issue out for yarn on why -P -D doesn't work and probably will never get to it.

You just read "When to use NPM's Peer Dependencies". Please share if you liked it!
You can read more recent posts here.