assets.ts
3.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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}`;
}