reactjsvitewebpack-module-federation

React Vite Module Federation remoteEntry.js "TypeError: Failed to fetch dynamically imported module"


Host application can't access the remoteEntry.js file of the remote app.

Remote config

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    federation({
      name: 'remote_app',
      filename: 'remoteEntry.js',
      exposes: {
        './App': './src/App',
      },
      shared: [
        ......
        'react',
        'react-dom',
        'react-query',
        'react-router-dom',
      ],
    }),
  ],
  build: {
    modulePreload: false,
    target: 'esnext',
    minify: false,
    cssCodeSplit: false,
  },
});

Host App

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    federation({
      name: 'app',
      remotes: {
        remoteApp: 'http://localhost:5001/assets/remoteEntry.js',
      },
      shared: ['react', 'react-dom'],
    }),
    
  ],
  build: {
    modulePreload: false,
    target: 'esnext',
    minify: false,
    cssCodeSplit: false,
  },
})

Commands ran on both app

npm run build

npm run dev


Solution

  • Getting remoteEntry.js access

    The issue is here is that npm run dev is the wrong command to use when running locally. To fix this, make sure you are running npm run preview on the remote app

    Accessing Modules

    Another issue you might run into if you are using TypeScript is loading the module. Make sure you put all modules you are declaring in a file called tsremote.d.ts the .d.ts is mandatory for this to pick up the remote modules.

    Then inside the tsremote.d.ts file you can declare what you want to access

    declare module 'remoteApp/App';