assets.ts 3.57 KB
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

/**
 * 获取子应用的基础 URL
 * 在微前端环境中,返回子应用的实际域名和端口
 * 在独立运行时,返回当前域名
 */
/**
 * 获取子应用的基础 URL
 * 在微前端环境中,返回子应用的实际域名和端口
 * 在独立运行时,返回当前域名
 */
export function getSubAppBaseUrl(): string {
  // 如果在 qiankun 环境中
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    // qiankun 会注入 __INJECTED_PUBLIC_PATH_BY_QIANKUN__,包含子应用的公共路径
    const publicPath = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
    
    if (publicPath) {
      // 从 publicPath 中提取基础 URL
      try {
        // 尝试将 publicPath 解析为完整 URL
        const url = new URL(publicPath);
        // 如果 publicPath 是完整 URL(包含协议),返回其 origin
        if (url.protocol.startsWith('http')) {
          return url.origin;
        }
      } catch {
        // URL 解析失败,说明 publicPath 可能是相对路径,继续下面的处理
      }
      
      // 在开发环境中,子应用通常运行在独立端口(如 8081)
      const isDev = (import.meta as any).env?.MODE === 'development';
      
      if (isDev) {
        // 开发环境:子应用运行在独立端口 8081(与 vite.config.ts 中的 PORT 一致)
        const devPort = '8081';
        const host = window.location.hostname;
        return `http://${host}:${devPort}`;
      }
      
      // 生产环境:如果 publicPath 是相对路径,说明可能是同域部署
      // 此时使用当前域名即可(资源应该在同一域名下)
      return window.location.origin;
    }
    
    // 如果无法从 publicPath 获取,根据环境判断
    const isDev = (import.meta as any).env?.MODE === 'development';
    if (isDev) {
      // 开发环境:使用默认端口
      const host = window.location.hostname;
      return `http://${host}:8081`;
    }
    
    // 生产环境:使用当前域名
    return window.location.origin;
  }
  
  // 独立运行时,返回当前域名
  return window.location.origin;
}

/**
 * 处理图片资源路径,确保使用子应用自己的域名
 * @param imagePath 图片路径,可以是相对路径(如 /images/xxx.png)或绝对路径(如 http://xxx/images/xxx.png)
 * @returns 处理后的完整图片 URL
 */
export function getImageUrl(imagePath: string): string {
  if (!imagePath) {
    return '';
  }
  
  // 如果已经是完整的 URL(包含 http:// 或 https://),直接返回
  if (/^https?:\/\//.test(imagePath)) {
    // 如果是完整 URL,检查是否是子应用的域名
    try {
      const url = new URL(imagePath);
      const baseUrl = getSubAppBaseUrl();
      const baseUrlObj = new URL(baseUrl, window.location.href);
      
      // 如果 URL 的域名和子应用的域名不同,需要替换为子应用的域名
      if (url.origin !== baseUrlObj.origin) {
        // 提取路径部分,使用子应用的域名
        return `${baseUrlObj.origin}${url.pathname}${url.search}${url.hash}`;
      }
      
      return imagePath;
    } catch {
      return imagePath;
    }
  }
  
  // 如果是相对路径(以 / 开头),拼接子应用的基础 URL
  if (imagePath.startsWith('/')) {
    const baseUrl = getSubAppBaseUrl();
    return `${baseUrl}${imagePath}`;
  }
  
  // 如果是相对路径(不以 / 开头),需要根据当前路径处理
  // 这里假设是相对于 public 目录的路径
  const baseUrl = getSubAppBaseUrl();
  return `${baseUrl}/${imagePath}`;
}