Multiple load of same library (react, preact) #2880
-
Please explain what and why this happens, i do not understand. new webpack.container.ModuleFederationPlugin({
name: 'shell',
filename: `shell.${version}.js`,
shared: {
preact: {
sharedKey: 'preact',
requiredVersion: ''10.22.1,
version: '10.22.1',
singleton: true
}
},
}), The remote application has the same configuration: new webpack.container.ModuleFederationPlugin({
name: 'remote',
filename: `remote.${version}.js`,
shared: {
preact: {
sharedKey: 'preact',
requiredVersion: ''10.22.1,
version: '10.22.1',
singleton: true
}
},
exposes: { './remoteApp': './src/App' },
}), This is how the shell app consumes remote: // append script
async #appendScript(url: string) {
return new Promise((resolve, reject) => {
const $script = document.createElement('script')
$script.src = url
$script.async = true
$script.onload = resolve
$script.onerror = () => {
$script.remove()
reject(`Cannot download script for ${url}`)
}
document.head.appendChild($script)
})
} // init module
async #resolveModule(scope: string, module: string) {
try {
await window[scope].init(__webpack_share_scopes__.default)
const factory = await window[scope].get(module)
return factory()
} catch (error) {
throw error
}
} // extract exposed component
async resolve(path: string) {
try {
const manifest = this.#getModuleManifest(path)
const { url, scope, module } = await ServiceResolver.getModuleMetadata(manifest)
await this.#appendScript(url)
const App = lazy(() => this.#resolveModule(scope, module))
return App
} catch (e) {
console.log(e)
}
} The shell app loads preact. Then we press a link which route element is exposed remote app, and preact is being loaded again. The problem is that inside remote app webpack uses preact loaded from remote, but in shell app preact loaded from shell. This is not a singleton and there is no sharing if preact was loaded twice. And of course, the are a lot of problem because of multiple instances of preact. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Use v2 not from webpack https://module-federation.io/ |
Beta Was this translation helpful? Give feedback.
Share scope is tearing because you are using dynamic remotes. It's a common problem in v1. Module-federation/runtime package provides the safe mechanics to use dynamic remotes. In v1 it will always tear if remotes are not loaded upfront before anything else takes place.
Someone is already using the share when new stuff is added to share scope. At that point it's too late for host to now use something else and remote will load it's own share as it wants since it's not too late for it.