1

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)

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

That’s interesting… however, would it not mean that federated applications would have to be run on the same physical machine then? Which would render the whole idea of remote federation kind of pointless wouldn’t it? I think when the host app is loading a remote module it should try to resolve its dependencies by looking at the available shared modules and if the remote module references a shared module it should resolve that using the shared module, and not from the remote application. If module federation is unable to achieve this, then what’s the point?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.