Reputation: 1925
I have an npm module which I'd like to share between my host and remote apps, but when I'm debugging the app, it is obvious that for example a singleton class (from the npm module) is instantiated twice, first the debugger hits the module loaded by the host app, and then the same thing happens but this time using the module loaded from the remote app.
I have set all the settings (singleton, requiredVersion, eager: true) as per documentation, versions perfectly match - what am I missing? Is there a working example I could look at? Thanks.
(Btw a very similar issue is described with more details here: WP5 Module Federation: Singleton instantiated multiple times)
Upvotes: 1
Views: 619
Reputation: 1925
Finally I got a break through. I went through my problem with a colleague who spotted that webpack doesn't emit any message for my library ('consume shared module / provide shared module') whereas such a message was there for react and other libraries. The library project didn't properly support ESM which caused webpack to exclude it (without an explicit error message which isn't ideal). Fixing the library to be CJS+ESM fixed the problem, only a single instance is loaded, Singletons finally work - happy days :)
Upvotes: 2
Reputation: 11
Of course I don't exactly know how your config and setup looks but I think the issue you're experiencing might arise because even though you have configured the module as a singleton in your Webpack Module Federation settings, both your host and remote applications are still loading their own individual copies of the npm module in question.
This probably results in two instances of what should be a singleton class.
To fix this you should have to get both instances to resolve the package to the same 'physical' location. You should be able to achieve this by setting up a monorepo using Yarn- or npm-Workspaces to hoists shared dependencies to the root node_modules directory.
For this you might want to look at this working example of a TypeScript Project Monorepo.
Upvotes: 0