originjs / vite-plugin-federation

Module Federation for vite & rollup
Other
2.39k stars 241 forks source link

React module federation gives __federation_shared_react-dom-6fc2ee8d.js:224 TypeError: Cannot read properties of null (reading 'useContext') at react_production_min.useContext (__federation_shared_react-af90d75c.js:59:144) #595

Open Elvis116 opened 7 months ago

Elvis116 commented 7 months ago

React module federation gives federation_shared_react-dom-6fc2ee8d.js:224 TypeError: Cannot read properties of null (reading 'useContext') at react_production_min.useContext (federation_shared_react-af90d75c.js:59:144) Is it due to the removal of singleton option in shared?

Elvis116 commented 7 months ago

To reproduce create a component based on @mui/x-date-pickers on remote project.

Elvis116 commented 7 months ago

The root component might be @mui/material/Popper. Can anyone help check it? Thanks.

Elvis116 commented 7 months ago

After further digging, it is caused by @mui/system/useThemeWithoutDefault. Not sure how to solve it in vite federation plugin, webpack module federation works fine.

FrancicoVerdu commented 7 months ago

Hi, I think your error is repeated Issue 294. When I have had the same problem I have solved it by adding to the host component the dependencies of the remote component, this is not an optimal solution but it can get you out of trouble.

nahimr commented 7 months ago

The root component might be @mui/material/Popper. Can anyone help check it? Thanks.

Same problem here, it looks like it's using useTheme that relies on useContext, also @originjs doesn't allow singleton shared dependencies. Which makes this library useless for big project.

DawiePritchard commented 7 months ago

I cannot stress enough how critical managing dependency versions is when using this plugin, especially when dealing with singleton patterns like React's context.

Recently, I encountered issues related to context API failures in a federated module which was indirectly caused by mismatched library versions. It turns out, the root cause was related to how versions were specified in package.json.

For instance, specifying a dependency version with a caret (^), such as react-router-dom:"^6.8.2", allows npm to install minor updates automatically. This can lead to scenarios where your lockfile points to a newer version than you explicitly tested with, like 6.23.0 in this case. Here’s what you might see in your yarn.lock or package-lock.json:

react-router-dom@^6.8.2:
  version "6.23.0"

This scenario highlights the importance of using exact versions in federated modules or at least being very deliberate about version ranges. In a federated environment, unexpected updates can lead to incompatibilities, especially if different versions of the same package end up being loaded in the host and remote apps.

A safer approach could be to remove the caret (^) and pin the dependencies to exact versions to prevent such issues in both your host and remote apps:

"react-router-dom": "6.8.2"

This ensures that all instances of the application, across different federated modules, use exactly the same version, reducing the risk of runtime errors due to version mismatches.

While this might reduce flexibility in quickly receiving updates, it adds a layer of reliability and predictability to your build and deployment processes in a federated architecture.

Hope this helps anyone struggling with similar issues, if anyone has any alternative solutions please let me know!

The plugin should ideally manage these dependencies more effectively, especially as the number of federated apps grows, making manual dependency management increasingly complex which is not an ideal scenario.

anshuman1490 commented 4 months ago

see this https://github.com/originjs/vite-plugin-federation/issues/596#issuecomment-2222071204

J-cyber-d commented 4 months ago

The root component might be @mui/material/Popper. Can anyone help check it? Thanks.

image

Please Help Me , If you get this issue from @mui/material ui popper

anshuman1490 commented 4 months ago

@J-cyber-d try to add date-picker and @emotion/styled in host and remote shared scope.

J-cyber-d commented 4 months ago

@J-cyber-d try to add date-picker and @emotion/styled in host and remote shared scope.

Host App vite.config.js file

import react from '@vitejs/plugin-react-swc';
import svgr from 'vite-plugin-svgr';
import federation from '@originjs/vite-plugin-federation';
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  //console.log('Loaded environment variables:', env);
  return {
    plugins: [
      react(),
      svgr(),
      federation({
        name: 'host',
        remotes: {
          PaymentApp: '',
          DmsApp: env.VITE_DMS_APP_URL,
          AssestManagement: env.VITE_AMS_APP_URL,
          WebAmsApp: 'http://localhost:6009/assets/remoteEntry.js',
          SampleAmsApp: 'http://localhost:6010/assets/remoteEntry.js',
        },
        shared: [
          'react',
          'react-dom',
          'react-router-dom',
          '@emotion/styled',
          '@mui/x-date-pickers',
        ],
      }),
    ],
    server: {
      proxy: {
        '/api': {
          target: env.VITE_APP_API_URL,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '/api'),
        },
      },
    },
    build: {
      modulePreload: true,
      target: 'esnext',
      minify: false,
      cssCodeSplit: false,
    },
  };
});

Remote app vite.config.js

import react from "@vitejs/plugin-react-swc";
import federation from "@originjs/vite-plugin-federation";

// https://vitejs.dev/config/
export default defineConfig({
  optimizeDeps: {
    include: ["@emotion/react", "@emotion/styled", "@mui/material/Tooltip"],
  },
  plugins: [
    react(),
    federation({
      name: "ipx-ams-web",
      filename: "remoteEntry.js",
      exposes: {
        "./AssestManagement": "./src/Components/marcho/Table",
      },
      shared: [
        "react",
        "react-dom",
        "react-router-dom",
        "@emotion/styled",
        "@mui/x-date-pickers",
      ],
    }),
  ],
  build: {
    modulePreload: true,
    target: "esnext",
    minify: false,
    cssCodeSplit: true,
  },
  // server: {
  //   port: 3000,
  //   open: true,
  // },
  // resolve: {
  //   alias: {
  //     "@": path.resolve(__dirname, "src"),
  //   },
  // },
  // css: {
  //   preprocessorOptions: {
  //     less: {
  //       javascriptEnabled: true,
  //     },
  //   },
  // },
  // esbuild: {
  //   jsxInject: import React from 'react',
  // },
  // optimizeDeps: {
  //   include: ["@ant-design/icons"],
  // },
});

image

Getting an Same Error Note : this error showing in latest mui version , so far it not showing before update the version

anshuman1490 commented 4 months ago

Here is my vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import federation from '@originjs/vite-plugin-federation'
import path from 'path'

const deps = require('./package.json').dependencies

export default defineConfig({
    plugins: [
        react({
            babel: {
                plugins: [
                    [
                        'babel-plugin-formatjs',
                        {
                            idInterpolationPattern: 'datastore_[sha512:contenthash:6]',
                            ast: true,
                        },
                    ],
                ],
            },
        }),
        federation({
            name: 'data-stores',
            filename: 'remoteEntry.js',
            exposes: {
                './App': './src/App',
            },
            shared: {
                react: {
                    singleton: true,
                    eager: true,
                    requiredVersion: deps['react'],
                },
                'react-dom': {
                    singleton: true,
                    eager: true,
                    requiredVersion: deps['react-dom'],
                },
                'react-router-dom': {
                    singleton: true,
                    eager: true,
                    requiredVersion: deps['react-router-dom'],
                },
                '@mui/x-data-grid-premium': {
                    singleton: true,
                    eager: true,
                    requiredVersion: deps['@mui/x-data-grid-premium'],
                },
                '@emotion/styled': {
                    singleton: true,
                    eager: true,
                    requiredVersion: deps['@emotion/styled'],
                },
            },
        }),
    ],
    build: {
        modulePreload: false,
        target: 'esnext',
        minify: false,
        cssCodeSplit: false,
        sourceMap: true,
        outDir: '../../../dist/remotes/data-stores',
    },
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
        },
    },
    base: '/data-stores/',
})
maangs commented 1 month ago

Does anyone have a working solution or work around for this? I can see that mui/material 5.15.10 is working but it breaks with 5.15.11

Codesleuth commented 4 days ago

Does anyone have a working solution or work around for this? I can see that mui/material 5.15.10 is working but it breaks with 5.15.11

I can confirm this is exactly where it falls over.

Package Host version Remote version Works?
@mui/material 5.15.10 5.15.10 :white_check_mark: YES
@mui/material 5.16.7 5.15.10 :white_check_mark: YES
@mui/material 5.16.7 5.15.11 :x: NO

All other packages, including react and react-dom, do not change any outcomes of this issue; it is completely isolated to @mui/material