dil*_*lli 4 reactjs redux react-redux webpack-5 webpack-module-federation
尝试将现有的 React + Redux 应用程序迁移到微前端。
Container (Parent App) - localhost:8080
ReactReduxApp (Child App - 1) - localhost:8081
ReactApp (Child App - 2) - localhost:8082
Run Code Online (Sandbox Code Playgroud)
独立应用程序可以在其端口中使用react-redux运行。当将其作为容器应用程序内的子应用程序访问时,容器应用程序未加载并抛出以下错误
Error: Could not find "store" in the context of "Connect(IndexPage)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(IndexPage) in connect options.
Run Code Online (Sandbox Code Playgroud)
没有ReactReduxApp(Child1),我的容器(父级)应用程序可以与ReactApp(Child2)正常运行
用于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
]
Run Code Online (Sandbox Code Playgroud)
在所有联合模块中使用此设置。
如果您的应用程序有自定义上下文,则有类似的解决方案。查看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} />
Run Code Online (Sandbox Code Playgroud)
官方 module-federation-examples monorepo 中有一个带有完整示例的应用程序,其中使用了这种方法:https://github.com/module-federation/module-federation-examples/tree/master/redux-reducer-injection
| 归档时间: |
|
| 查看次数: |
11517 次 |
| 最近记录: |