You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Vite Module Federation报错:无法获取动态导入模块,宿主应用无法访问remoteEntry.js

React Vite Module Federation 报错:TypeError: Failed to fetch dynamically imported module

宿主应用无法访问远程应用的remoteEntry.js文件,抛出TypeError: Failed to fetch dynamically imported module错误。

远程应用配置

// 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,
  },
});

宿主应用配置

// 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,
  },
})

执行命令

  • 两个应用均执行:npm run build
  • 两个应用均执行:npm run dev

排查与解决步骤

  1. 验证远程服务可用性
    直接在浏览器访问http://localhost:5001/assets/remoteEntry.js,确认能正常加载文件。如果返回404,检查远程应用的启动端口是否为5001,或资源路径是否配置错误。

  2. 核对资源输出路径
    查看远程应用build后的dist文件夹结构,确认remoteEntry.js的实际位置。如果文件直接在dist根目录,宿主配置的路径应改为http://localhost:5001/remoteEntry.js。

  3. 解决跨域问题
    若宿主与远程应用端口不同,在远程应用的Vite配置中添加CORS允许:

    server: {
      cors: true,
      port: 5001
    }
    
  4. 调整开发模式流程
    Vite Module Federation在开发模式下无需提前执行npm run build,直接启动npm run dev即可。删除两个应用的dist文件夹后重新启动开发服务测试。

  5. 统一共享依赖版本
    确保宿主与远程应用的react、react-dom等共享依赖版本完全一致,版本差异可能导致动态导入失败。

内容的提问来源于stack exchange,提问作者Joshua Duxbury

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:32:40