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

使用Native Federation加载Angular远程微前端触发NG0203错误

解决Angular Native Federation远程微前端的NG0203错误

从错误栈能看到,你的Shell应用使用@angular/core 17.2.1,远程应用使用@angular/core 17.3.10,核心依赖版本不一致是触发该错误的核心原因之一。结合Native Federation场景,以下是针对性解决方案:

1. 统一Shell和Remote的Angular核心依赖版本

Angular注入上下文对版本一致性要求极高,不同小版本的核心包会导致注入器不兼容。在两个项目中分别执行命令,统一版本:

# 升级到17.3.10(或替换为17.2.1进行降级)
ng update @angular/core@17.3.10 @angular/cli@17.3.10

2. 修正Native Federation共享依赖配置

检查两个项目的module-federation.config.js,确保核心Angular包设置为单例共享且严格版本匹配:

Shell项目共享配置

shared: {
  "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  // RxJS等其他共享依赖也按此规则配置
}

Remote项目共享配置

shared: {
  "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
  // 保持与Shell一致的共享规则
}

singleton: true确保全局仅存在一个核心依赖实例,strictVersion: true会拒绝版本不匹配的依赖加载,避免上下文冲突。

3. 确保动态加载逻辑在注入上下文内执行

如果通过ViewContainerRef.createComponent动态加载远程组件,需将逻辑包裹在runInInjectionContext中,确保注入器上下文正确:

import { inject, runInInjectionContext, Injector } from '@angular/core';

// 动态加载远程组件的示例函数
loadRemoteComponent() {
  const injector = inject(Injector);
  runInInjectionContext(injector, () => {
    // 在此执行远程组件的加载与创建逻辑
    this.viewContainer.createComponent(remoteComponentFactory);
  });
}

4. 确认独立组件的暴露配置

远程组件作为独立组件,需在module-federation.config.js的exposes中正确声明,且组件本身标记standalone: true:

Remote项目暴露配置

exposes: {
  './RemoteComponent': './src/app/remote-component/remote-component.component.ts',
},

远程组件代码

@Component({
  selector: 'app-remote-component',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './remote-component.component.html',
})
export class RemoteComponent {}

内容的提问来源于stack exchange,提问作者Rogger Aldair Paredes Tavara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:02:09