【问题标题】:Webpack 5 Module federation micro-frontend and react-redux is not workingWebpack 5 Module federation micro-frontend 和 react-redux 不工作
【发布时间】:2021-08-15 09:22:33
【问题描述】:

尝试将现有的 react + redux 应用程序迁移到微前端。

Container (Parent App) - localhost:8080
ReactReduxApp (Child App - 1) - localhost:8081
ReactApp (Child App - 2) - localhost:8082

独立应用程序可以在其 PORT 中使用 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.

没有 ReactReduxApp(Child1) 我的 Container(Parent) 应用在 ReactApp(Child2)

下运行良好

【问题讨论】:

    标签: reactjs redux react-redux webpack-5 webpack-module-federation


    【解决方案1】:

    解决方案

    为每个使用 React Context 的共享库使用 singleton: true

    // 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 中的example

    说明

    Such errors arise when you have two copies of React Context in your apps。 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

    【讨论】:

      【解决方案2】:

      也许你应该试试这个 redux-micro-frontend 而不是 origin redux

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 2021-10-23
        • 1970-01-01
        • 2021-02-10
        • 2021-10-04
        • 2018-02-11
        • 2020-07-24
        • 2021-09-11
        • 2021-09-03
        相关资源
        最近更新 更多