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

Angular微前端Module Federation远程应用资源404问题求助

解决Angular Module Federation远程应用字体资源404问题

核心原因

宿主应用加载远程模块时,远程模块内的字体资源默认会使用宿主应用的域名发起请求,而非远程应用的部署地址,最终导致404错误。以下是无需将远程assets复制到宿主的解决方案:

方案1:配置远程应用的publicPath

通过设置webpack的publicPath,让远程模块的资源引用路径指向自身部署地址,有两种配置方式:

方式A:固定绝对地址(适合部署地址固定场景)

修改远程应用的webpack配置,在withModuleFederationPlugin中添加publicPath:

const { share, withModuleFederationPlugin } = require('@angular-architects/module-federation/webpack');

const webpackConfig = withModuleFederationPlugin({
  name: 'shareholders',
  exposes: {
    './PagesModule': './src/app/pages/pages.module.ts',
  },
  // 替换为你的远程应用部署根地址
  publicPath: 'http://your-remote-app-domain:port/',
  shared: share({
    // ... 你的shared配置
  }),
});

module.exports = webpackConfig;

方式B:自动推断路径(适合动态部署场景)

如果远程应用部署地址不固定,可设置publicPath: 'auto',webpack会自动从加载远程模块的脚本地址推断资源路径:

const webpackConfig = withModuleFederationPlugin({
  // ... 其他配置
  publicPath: 'auto',
});

// 也可直接修改output配置
webpackConfig.output.publicPath = 'auto';

方案2:为远程应用的assets设置独立输出目录

避免远程资源路径与宿主冲突,同时配合publicPath确保路径正确:

  1. 修改远程应用的angular.json,为assets指定独立输出目录:
{
  "projects": {
    "shareholders": {
      "architect": {
        "build": {
          "options": {
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets/shareholders/"
              }
            ],
            // ... 其他build配置
          }
        }
      }
    }
  }
}
  1. 确保远程应用的publicPath配置正确,此时字体资源的请求路径会变为http://remote-domain/assets/shareholders/fonts/xxx.ttf,不会被宿主域名拦截。

方案3:检查CSS中的字体引用路径

确保远程模块的CSS中字体引用使用相对路径,webpack会自动结合publicPath转换为正确的绝对路径:

@font-face {
  font-family: 'CustomFont';
  src: url('../assets/fonts/custom-font.ttf') format('truetype');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:40:24