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

React+Typescript Module Federation加载脚本失败问题求助

解决Module Federation加载remoteEntry.js失败问题

问题重现

使用create-mf-app生成React+TypeScript的Module Federation基础脚手架,仅新增一个仅包含<p>标签的Cookie.tsx组件,运行时出现以下错误:

Loading script failed.
(missing: http://localhost:8081/remoteEntry.js)
while loading "./Cookie" from webpack/container/reference/app1
ScriptExternalLoadError: Loading script failed.
(missing: http://localhost:8081/remoteEntry.js)
while loading "./Cookie" from webpack/container/reference/app1
    at webpack/container/reference/app1 (http://localhost:8080/main.js:79:25)
    at __webpack_require__ (http://localhost:8080/runtime.js:36:33)
    at initExternal (http://localhost:8080/runtime.js:316:28)
    at __webpack_require__.I (http://localhost:8080/runtime.js:329:15)
    at http://localhost:8080/runtime.js:821:47
    at webpack/sharing/consume/default/react/react (http://localhost:8080/runtime.js:875:67)
    at http://localhost:8080/runtime.js:906:56
    at Array.forEach (<anonymous>)
    at __webpack_require__.f.consumes (http://localhost:8080/runtime.js:889:36)
    at http://localhost:8080/runtime.js:122:40

排查与解决步骤

1. 确认远程应用状态

  • 检查远程应用(app1)是否在http://localhost:8081正常启动,直接访问http://localhost:8081/remoteEntry.js,能下载到文件才说明服务正常。
  • 若远程应用未启动,先启动;若端口不符,调整主/远程应用的配置端口,保持一致。

2. 核对Module Federation配置

远程应用(app1)webpack配置

确保ModuleFederationPlugin正确暴露组件且filename为remoteEntry.js:

new ModuleFederationPlugin({
  name: 'app1',
  filename: 'remoteEntry.js',
  exposes: {
    './Cookie': './src/Cookie.tsx', // 路径和组件文件名必须完全匹配
  },
  shared: {
    react: { singleton: true, requiredVersion: '^18.0.0' },
    'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
  },
});

主应用webpack配置

确保主应用引用的远程地址端口、文件名无误:

new ModuleFederationPlugin({
  name: 'host',
  remotes: {
    app1: 'app1@http://localhost:8081/remoteEntry.js', // 地址需和远程应用完全一致
  },
  shared: {
    react: { singleton: true, requiredVersion: '^18.0.0' },
    'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
  },
});

3. 检查组件导入路径

主应用导入Cookie时,路径必须和远程应用exposes里的键完全匹配:

// 正确写法
import Cookie from 'app1/Cookie';
// 错误写法(路径不匹配会导致webpack无法定位模块)
import Cookie from 'app1/src/Cookie';

4. 清理缓存重启服务

  • 删除主/远程应用的node_modules/.cache目录,或启动服务时加--no-cache参数清理webpack缓存。
  • 完全重启两个应用的开发服务,避免热更新导致配置未生效。

5. 配置TypeScript类型(TS项目专属)

在主应用tsconfig.json中添加路径映射,确保TypeScript能解析远程模块:

{
  "compilerOptions": {
    "paths": {
      "app1/*": ["./src/types/app1/*"]
    }
  }
}

同时在src/types/app1/index.d.ts中声明远程模块类型:

declare module 'app1/Cookie' {
  import type React from 'react';
  const Cookie: React.FC;
  export default Cookie;
}

内容的提问来源于stack exchange,提问作者Senthil SK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:32:50