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

Angular 14模块联邦:如何在远程应用内获取自身绝对路径?

解决Angular 14模块联邦远程应用获取绝对路径的问题

方法1:使用Webpack的__webpack_public_path__变量

模块联邦加载远程应用时会自动设置__webpack_public_path__,该变量的值就是远程应用的基础绝对路径,直接使用即可:

首先在项目src目录下创建typings.d.ts文件,添加类型声明避免TypeScript报错:

declare let __webpack_public_path__: string;

然后修改SettingsService的init方法:

public init() {
  // 可选:去掉路径末尾的斜杠,避免拼接时出现重复斜杠
  const absolutePath = __webpack_public_path__.replace(/\/$/, '');
  this.configuration = initFile(`${absolutePath}/config.json`);
}

方法2:从远程入口Script标签提取路径

如果不想依赖Webpack内部变量,可以通过查找加载远程应用的remoteEntry.js脚本标签,提取其所在的基础路径:

public init() {
  // 根据实际remoteEntry文件名调整匹配规则
  const remoteEntryScript = Array.from(document.scripts).find(script => 
    script.src.includes('remoteEntry.js')
  );

  if (remoteEntryScript) {
    // 截取脚本路径的目录部分作为绝对路径
    const absolutePath = remoteEntryScript.src.substring(0, remoteEntryScript.src.lastIndexOf('/'));
    this.configuration = initFile(`${absolutePath}/config.json`);
  } else {
    // 本地开发或找不到脚本时的 fallback 逻辑
    this.configuration = initFile('/config.json');
  }
}

方法3:通过环境变量传递路径(固定部署场景适用)

如果远程应用的部署路径固定,可在构建时通过环境变量注入:

  1. 在远程应用的src/environments/environment.ts中添加路径配置:
export const environment = {
  production: false,
  remoteBasePath: 'http://localhost:4201' // 本地开发路径
};
  1. 生产环境在environment.prod.ts中替换为实际部署路径:
export const environment = {
  production: true,
  remoteBasePath: 'https://your-remote-app-domain.com'
};
  1. 在SettingsService中直接使用:
import { environment } from '../environments/environment';

// ...

public init() {
  const absolutePath = environment.remoteBasePath;
  this.configuration = initFile(`${absolutePath}/config.json`);
}

注意事项

  • 方法1是最适配模块联邦机制的方案,__webpack_public_path__会自动适配不同部署路径,无需手动维护。
  • 方法2通用性更强,不依赖Webpack内部机制,但需要确保remoteEntry.js的文件名匹配规则正确。
  • 方法3适合部署路径固定的场景,灵活性稍弱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:40:57