utils.ts
3.52 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/**
* qiankun 工具函数模块
* 提供一些常用的微前端相关工具函数
*/
/**
* 判断当前是否在微应用环境中运行
*/
export function isInMicroApp(): boolean {
return !!(window as any).__POWERED_BY_QIANKUN__;
}
/**
* 获取微应用公共路径
* @param appName 应用名称
*/
export function getPublicPath(appName?: string): string {
if (isInMicroApp()) {
return (window as any).__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || '/';
}
return appName ? `/${appName}/` : '/';
}
/**
* 微应用通信:发送消息到主应用
* @param type 消息类型
* @param data 消息数据
*/
export function sendMessageToMain(type: string, data?: any) {
if (isInMicroApp()) {
const props = (window as any).__QIANKUN_PROPS__;
if (props?.onGlobalStateChange) {
props.setGlobalState?.({
type,
data,
timestamp: Date.now(),
});
}
} else {
console.warn('[qiankun utils] 当前不在微应用环境中,无法发送消息');
}
}
/**
* 微应用通信:监听主应用消息
* @param callback 回调函数
*/
export function listenMainMessage(callback: (state: any, prev: any) => void) {
if (isInMicroApp()) {
const props = (window as any).__QIANKUN_PROPS__;
if (props?.onGlobalStateChange) {
props.onGlobalStateChange(callback);
}
} else {
console.warn('[qiankun utils] 当前不在微应用环境中,无法监听消息');
}
}
/**
* 格式化微应用路径
* @param path 路径
* @param base 基础路径
*/
export function formatMicroAppPath(path: string, base: string = ''): string {
const normalizedBase = base.replace(/\/+$/, '');
const normalizedPath = path.replace(/^\/+/, '');
return `${normalizedBase}/${normalizedPath}`;
}
/**
* 检查微应用是否激活
* @param activeRule 激活规则
* @param currentPath 当前路径
*/
export function isMicroAppActive(
activeRule: ((location: Location) => boolean) | string,
currentPath: string = window.location.pathname,
): boolean {
if (typeof activeRule === 'function') {
return activeRule(window.location);
}
return currentPath.startsWith(activeRule);
}
/**
* 安全地调用微应用方法
* @param appName 应用名称
* @param method 方法名
* @param args 参数
*/
export async function callMicroAppMethod(
appName: string,
method: string,
...args: any[]
): Promise<any> {
try {
const app = (window as any).__QIANKUN_APPS__?.[appName];
if (app && typeof app[method] === 'function') {
return await app[method](...args);
}
console.warn(`[qiankun utils] 微应用 ${appName} 的方法 ${method} 不存在`);
return null;
} catch (error) {
console.error(`[qiankun utils] 调用微应用方法失败:`, error);
throw error;
}
}
/**
* 预加载微应用资源
* @param entry 微应用入口
*/
export function prefetchMicroApp(entry: string): Promise<void> {
return new Promise((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = entry;
link.addEventListener('load', () => resolve());
link.onerror = () => reject(new Error(`预加载失败: ${entry}`));
document.head.append(link);
});
}
/**
* 获取微应用加载性能数据
*/
export function getMicroAppPerformance() {
const performance = (window as any).__QIANKUN_PERFORMANCE__;
if (performance) {
return {
loadTime: performance.loadTime || 0,
mountTime: performance.mountTime || 0,
totalTime: (performance.loadTime || 0) + (performance.mountTime || 0),
};
}
return null;
}