utils.ts 3.43 KB
/**
 * 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.addEventListener("error", () => 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;
}