Setup:
Package models
- Common mongoose models used across multiple apps
- peerDependencies: "mongoose"
Package app
- dependencies: "mongoose", "models"
- Linked with models through
app> npm link models
Issue:
When developing models
, I need mongoose installed under node_modules
, otherwise it can't find mongoose.
However, when using models
under app
, if mongoose exists under node_modules
in models
, it uses that copy instead of sharing the same instance of mongoose with app
.
The way I'm making this work now is installing mongoose when developing models
, then deleting it when using it under app
. I've looked into parent-require
but this seems to only solve the issue with npm link not finding the package from the parent, not the issue with having to remove/install the node_module (or am I doing this incorrectly?)
Related: Sharing a Mongoose instance between multiple NPM packages
In case you get an error
... call
npm link <required module>
in your module's root dirE.g. I had the same issue with peerDependency react. So I did
npm link reack
for my local module and it worked.Here is a module that you can use that deals with parent and grandparent modules that are linked
I've taken to using
require.main.require
instead ofrequire
for modules that need a shared instance.For example,
require.main.require('mongoose')
will guarantee only the top-level mongoose is used.