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

Angular 19 + Webpack 5 Module Federation遇export语法错误求助

Angular 19 + Webpack 5 Module Federation 加载问题解决

核心问题定位

remoteEntry.js 被浏览器当作普通脚本加载,而非 ES 模块,导致 export 语法报错。

解决方案步骤

1. 配置 Remote 应用输出为 ES 模块

在 remote-app 的 webpack.config.js 中,修改 output 和 Module Federation 插件配置:

output: {
  filename: '[name].js',
  library: {
    type: 'module' // 关键:将输出指定为 ES 模块
  },
  chunkFormat: 'module'
},
plugins: [
  new ModuleFederationPlugin({
    name: 'remoteApp',
    filename: 'remoteEntry.js',
    exposes: {
      './RemoteComponent': './src/app/remote/remote.component.ts'
    },
    shared: {
      '@angular/core': { singleton: true, strictVersion: true },
      '@angular/common': { singleton: true, strictVersion: true },
      '@angular/router': { singleton: true, strictVersion: true }
    }
  })
]

2. 调整 Host 应用的远程模块加载逻辑

在 host-app 的 app.routes.ts 中,明确指定加载类型为模块:

import { loadRemoteModule } from '@angular-architects/module-federation';

const routes: Routes = [
  {
    path: 'remote',
    loadChildren: () =>
      loadRemoteModule({
        type: 'module', // 声明加载的是 ES 模块
        remoteEntry: 'http://localhost:4201/remoteEntry.js',
        exposedModule: './RemoteComponent'
      }).then(m => m.RemoteModule)
  }
];

3. 统一 tsconfig.json 配置

确保两个应用的 tsconfig.json 启用 ES 模块相关编译选项:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2022",
    "esModuleInterop": true
  }
}

4. 检查手动引入的脚本类型

如果 Host 应用的 index.html 手动引入了 remoteEntry.js,必须添加 type="module" 属性:

<script type="module" src="http://localhost:4201/remoteEntry.js"></script>

(使用 @angular-architects/module-federation 自动加载时可跳过此步骤)

额外排查点

  • 确认 remote-app 启动后,remoteEntry.js 的响应头 Content-Type 为 application/javascript,而非 text/plain
  • 执行 ng clean 清除 Angular 构建缓存,再重新构建两个应用

内容的提问来源于stack exchange,提问作者Santosh Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:52:03