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

Angular 16添加@angular-architects/module-federation后运行时报错

问题解决方案

针对你在Angular 16现有项目中引入@angular-architects/module-federation@16.0.4后遇到的两个浏览器控制台错误,以下是具体的排查和修复方案:

1. 解决 Error: Shared module is not available for eager consumption

这个错误的核心原因是:项目中存在急切导入的模块(比如在main.ts、根模块app.module.ts顶层直接import的模块),但这些模块被标记为模块联邦的共享模块,而共享模块默认以懒加载方式处理,两者产生冲突。

修复步骤:

  • 打开项目根目录的webpack.config.js(或module-federation.config.js),找到shared配置节点。
  • 对所有在项目中被急切导入的共享模块,添加eager: true配置,示例如下:
shared: {
  "@angular/core": { singleton: true, strictVersion: true, eager: true },
  "@angular/common": { singleton: true, strictVersion: true, eager: true },
  "@angular/router": { singleton: true, strictVersion: true, eager: true },
  // 自定义共享模块同理,若存在急切导入则添加eager: true
}
  • 检查项目中是否有自定义模块被设为共享,但又在根文件中直接导入,这种情况要么给该模块的共享配置加eager: true,要么将其改为懒加载方式导入。

2. 解决 Cannot use 'import.meta' outside a module

这个错误是因为现有项目的模块格式配置不符合模块联邦的要求,import.meta是ES模块特有的语法,若项目配置为CommonJS等非ES模块格式则会报错。

修复步骤:

  • 打开tsconfig.app.json,修改compilerOptions中的模块配置:
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler", // Angular 16推荐使用bundler作为模块解析策略
    "target": "ES2020",
    // 保留其他原有配置
  }
}
  • 检查angular.json中对应项目的构建配置,确保使用Angular 16默认的ESBuild构建器,且无禁用ES模块的设置:
"projects": {
  "Application": {
    "architect": {
      "build": {
        "builder": "@angular-devkit/build-angular:browser-esbuild",
        "options": {
          // 确保未配置output为CommonJS等非ES模块格式
        }
      }
    }
  }
}
  • 清理编译缓存并重启服务:
ng cache clean
ng serve

额外排查建议

因为新项目可以正常运行,你可以对比新项目与现有项目的以下文件配置,确保现有项目符合模块联邦的启动要求:

  • 检查main.ts是否改为模块联邦兼容的动态导入启动逻辑,示例:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

Promise.all([import('./bootstrap')]).then(() => {
  bootstrapApplication(AppComponent, appConfig)
    .catch(err => console.error(err));
});
  • 确认bootstrap.ts文件存在且配置正确,该文件是模块联邦的启动入口文件。

内容的提问来源于stack exchange,提问作者Krish Dunn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:58:28