解决方案
用于singleton: true
每个使用 React Context 的共享库:
// webpack.config.js
// import package.json to get packages' versions
const deps = require('./package.json').dependencies
module.exports = {
// ...
plugins: [
new ModuleFederationPlugin({
name: 'main',
filename: 'remoteEntry.js',
remotes: {
// your remotes config
},
shared: {
react: {
singleton: true,
version: deps['react']
},
'react-dom': {
singleton: true,
version: deps['react-dom']
},
'react-router-dom': {
singleton: true,
version: deps['react-router-dom']
},
'react-redux': {
singleton: true,
version: deps['react-router-dom']
}
},
}),
// other plugins
]
在所有联合模块中使用此设置。
自定义上下文的解决方案
如果您的应用程序具有自定义上下文,则有类似的解决方案。查看module-federation-examples monorepo 中的示例。
解释
当您的应用程序中有两个 React Context 副本时,就会出现此类错误。Redux、React Router、Material UI 和其他库在其提供程序中使用 Context API。因此,例如,当您在两个 WP5 联合模块中导入 Redux 时,每个模块(或应用程序)都有自己的 Redux 副本,即使它的版本相同。
解决方法
如果由于某种原因你不能有单例模块,有一个解决方法:将你的 Redux 存储传递给远程应用程序的 props 并用另一个 Provider 包装它,如下所示:
// in your remote app:
const RemoteAppWrapper = ({ store }) => {
return (
<Provider store={store}>
<RemoteApp />
</Provider>
);
};
// and then in your host app:
<RemoteApp store={store} />
在官方 module-federation-examples monorepo 中有一个带有完整示例的应用程序,其中使用了这种方法:https ://github.com/module-federation/module-federation-examples/tree/master/redux-reducer-injection