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

使用Module Federation插件暴露远程组件时遇模块未找到错误求助

问题描述

尝试用Module Federation插件将组件暴露为远程资源时,遇到以下错误:

container entry:AppComponent[0] - Error: Module not found: Error: Can't resolve './src/app/app.component.ts' in '/src/main/webapp'

我的webpack.config.js配置如下:

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
const mf = require('@angular-architects/module-federation/webpack');
const path = require('path');
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(path.join(__dirname, '../../tsconfig.json'), [
  /* mapped paths to share */
]);
module.exports = {
  output: {
    uniqueName: 'myApp',
    publicPath: 'auto',
    scriptType: 'text/javascript'
  },
  optimization: {
    runtimeChunk: false
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases()
    },
 
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "my_app",
      filename: "my_app.js",
       exposes: {
        "AppComponent": './src/app/app.component.ts'
      },
      
      shared: share({
        '@angular/core': { singleton: true, strictVersion: true, requiredVersion: '12.2.17' },
        '@angular/common': { singleton: true, strictVersion: true, requiredVersion: '12.2.17' },
        '@angular/router': { singleton: true, strictVersion: true, requiredVersion: '12.2.17' },

        ...sharedMappings.getDescriptors()
      })
    }),
    sharedMappings.getPlugin()
  ]
};
解决方案

1. 校验文件相对路径

错误核心是webpack找不到指定路径的文件,先核对./src/app/app.component.ts是否对应真实文件位置:

  • 假设你的webpack.config.js在/src/main/webapp/目录下,那么当前配置的路径会指向/src/main/webapp/src/app/app.component.ts,如果实际组件文件在/src/app/app.component.ts,需要把路径改成../../src/app/app.component.ts。

2. 改用绝对路径或别名

用path模块拼接绝对路径,彻底避免相对路径混乱:

exposes: {
  "AppComponent": path.join(__dirname, './src/app/app.component.ts')
}

或者在resolve配置里加别名简化路径:

resolve: {
  alias: {
    '@app': path.join(__dirname, './src/app'),
    ...sharedMappings.getAliases()
  }
}

之后在exposes里直接用别名:

exposes: {
  "AppComponent": '@app/app.component.ts'
}

3. 调整Angular的暴露方式

在Angular+Module Federation场景下,优先暴露NgModule而非单个组件——组件必须在模块中声明才能被远程应用正确加载。修改暴露配置为模块文件:

exposes: {
  "AppModule": './src/app/app.module.ts'
}

远程应用导入该模块后,即可使用其中的组件。

4. 检查sharedMappings配置

如果tsconfig.json里有自定义路径映射,确保sharedMappings正确注册了这些路径,防止模块解析时出现冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:25:03