In a monorepo, if you have a dependency in one package can you use that dependency in another package without adding it to that package? For more clarity, check the below layout.
Project
|-packages
|- packageA
|- package.json (Here let say I have lodash dependency)
|- index.js
|- packageB
|-package.json (I haven't added lodash here.)
|- index.js
So, can I import lodash in packageB's index.js or do I have to add it there?
If packageB
use lodash, you should list lodash in the package.json
file of packageB
. If you don't, bad things could happen. For example, consider the following situations:
packageA
. In your case, you mentioned that packageA
lists lodash as a dependency. However, if down the road you refactored packageA
where it no longer needs lodash, you might remove it thinking that it is unused. If packageB
was relying on packageA
installing lodash, then packageB
would break due to the missing dependency.packageB
is installed without packageA
. Without knowing what your packages contain it's hard to know for sure, but it is possible that now or down the road you (or someone else) could install packageB
without installing packageA
. You would then wind up with the same situation where lodash is not installed and packageB
would break.packageA
updates to a new major version of lodash. If packageB
is no longer compatible with the new major version of lodash, it could break. This would not be a problem if packageB
specified it's own dependency on lodash as you could update them together or separately depending on what is best.Other situations could happen, these are just a few examples.
Note, you could specify lodash as a peer dependency in both packageA
and packageB
letting the consuming application install lodash so you don't have to install it in both packages, but that doesn't really simplify things either in your monorepo or in your consuming applications.