我最近制作了一个联合模块主机,用于联合站点的页眉和页脚。一切都按预期工作,但如果对联合主机的请求失败,我会尝试构建一些后备。
new ModuleFederationPlugin({
name: 'app',
remotes: {
app2: 'app2@https:/example.com/remoteEntry.js',
},
shared: { react: { singleton: true, eager: true }, 'react-dom': { singleton: true, eager: true } },
}),
如果我阻止对 https:/example.com/remoteEntry.js 的请求,我会收到下面的 webpack 错误。理想情况下,我想加载一个基本的后备标题,或者只是没有标题,而不是页面完全死掉(error: https://example.com/remoteEntry.js1)
while loading "./Footer" from webpack/container/reference/app2
最佳答案
我知道这有点晚了,但我开发了这个解决方案,它可能可以帮助其他人使用 Webpack@5 和 Module Federation。它也基于动态 Remote 。
https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes
new ModuleFederationPlugin({
name: "app",
remotes: {
app2: `promise new Promise(resolve => {
// This part depends on how you plan on hosting and versioning your federated modules
const remoteUrlWithVersion = 'https:/example.com/remoteEntry.js'
const script = document.createElement('script')
script.src = remoteUrlWithVersion
script.onload = () => {
// the injected script has loaded and is available on window
// we can now resolve this Promise
const proxy = {
get: (request) => {
// Note the name of the module
return window.app2.get(request);
},
init: (arg) => {
try {
// Note the name of the module
return window.app2.init(arg)
} catch(e) {
console.log('remote container already initialized')
}
}
}
resolve(proxy)
}
script.onerror = (error) => {
console.error('error loading remote container')
const proxy = {
get: (request) => {
// If the service is down it will render this content
return Promise.resolve(() => () => "I'm dead");
},
init: (arg) => {
return;
}
}
resolve(proxy)
}
// inject this script with the src set to the versioned remoteEntry.js
document.head.appendChild(script);
})
`
},
exposes: {},
shared: {
...deps,
react: {
singleton: true,
eager: true,
requiredVersion: deps.react,
},
"react-dom": {
singleton: true,
eager: true,
requiredVersion: deps["react-dom"],
},
},
}),
关于javascript - 网络调用失败的 Webpack5 模块联合后备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64582404/