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

Angular 15联邦模块遇‘Shared module无法预加载’错误求助

解决Angular 15 Module Federation中@angular/common的共享模块加载错误

问题根源分析

你遇到的Shared module is not available for eager consumption错误,核心是@angular/common的共享配置存在格式错误(多余的末尾斜杠),且子模块@angular/common/http的重复配置触发了webpack模块共享逻辑冲突,同时直接设置eager: true违反了Angular CLI的编译逻辑。

具体解决方案

1. 修正@angular/common的共享配置格式

移除@angular/common/末尾的斜杠,并将子模块@angular/common/http整合到主模块的共享配置中,避免重复定义:

module.exports = withModuleFederationPlugin({
    name: 'mfe1',
    exposes: {
        './FederatedModule': './src/app/federation/federated.module.ts',
    },

    shared: share({
        '@angular/core': { singleton: true, requiredVersion: '^15.0.0', strictVersion: true },
        '@angular/common': { 
            singleton: true, 
            requiredVersion: '^15.0.0', 
            strictVersion: true,
            // 让子模块继承主模块的共享规则,避免单独配置引发冲突
            include: ['@angular/common/http']
        },
        '@angular/router': { singleton: true, requiredVersion: '^15.0.0', strictVersion: true },
    }),
});

如果所有依赖版本统一,也可以用shareAll简化配置:

shared: shareAll({ singleton: true, strictVersion: true, requiredVersion: '^15.0.0' }),

2. 确保懒加载bootstrap的正确性

确认main.ts严格遵循异步懒加载模式,不要在顶部直接导入任何Angular模块/组件:

import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

// 仅通过异步导入加载启动逻辑
import('./bootstrap').catch(err => console.error(err));

bootstrap.ts保持标准启动逻辑:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

3. 排查提前加载的依赖

检查项目中是否有第三方库或自定义代码在main.ts等早期执行文件中直接导入@angular/common的内容(比如CommonModule、HttpClient),这类提前导入会触发共享模块的eager加载。将此类导入移到懒加载的模块内部(如AppModule或组件中)。

4. 解决多版本Angular的inject()错误

移除@angular/common共享配置后出现的inject() must be called from an injection context错误,是因为host和remote加载了不同版本的@angular/common实例。修正后的共享配置中,strictVersion: true强制要求版本完全匹配,singleton: true确保全局只有一个模块实例,从根源解决该问题。

验证步骤

  1. 清理host和remote项目的node_modules、dist目录
  2. 重新安装依赖:npm install
  3. 启动remote应用,确认Shared module is not available for eager consumption错误消失
  4. 启动host应用加载remote模块,确认inject()错误不再出现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:43:38