Reputation: 81
I was following this tutorial , and tried to share a library between the shell and the mfe1 app. I created the lib outside the workspace directory with one service injected in root, then added it to the tutorial package.json, and imported it in both shell and mfe1. Inside both projects webpack config, i added the following configuration
new ModuleFederationPlugin({
.....
},
shared: {
.....
"my-lib": { singleton: true, strictVersion: true, requiredVersion: '1.0.0'},
...sharedMappings.getDescriptors()
}
}),
When testing the shell, i noticed that the singleton service is being initiated twice, first time when loading the shell, second time when moving to the mfe1, maybe i'm missing something, but isn't the purpose of singleton: true
config is to insure that only one instance of that service is existing?
Upvotes: 8
Views: 5136
Reputation: 2907
With the federation module plugin when the singleton property is set to true on a shared library it means that the lib is only loaded once even if it is required by multiple mfes. The strictVersion: true will cause an error if your mfes or shell require different version of the library.
This is not related to the angular sevices, even if the lib is only loaded once, it doesn't mean that its services will be singletons.
If you want a service to be a singleton accross multiple modules you should make sure that you provide the service in the root injector by adding :
@Injectable({
providedIn: 'root'
})
Or by making sure that the service is declared as a provider of the shell app module, and is not declared as a provider in any other modules.
Upvotes: 7