Wujie 微前端
项目使用 wujie-vue3 1.0.26 作为微前端框架。
什么是 Wujie
Wujie(无界)是腾讯优图实验室推出的一款基于 Web Components 的微前端框架,具有以下特点:
- 隔离性好:主应用和子应用完全隔离
- 性能优秀:预加载、保活策略
- 接入简单:一行代码即可接入子应用
- 兼容性强:支持 Vue 2/3、React、Angular 等各类框架
目录结构
src/utils/wuJie/ # 注意是大写 J
├── apps.ts # 子应用配置
├── config.ts # 配置获取工具
├── lifecycle.ts # 生命周期钩子
├── plugins.ts # 插件配置
├── preload.ts # 预加载逻辑
└── healthCheck.ts # 健康检查基本配置
子应用配置
// src/utils/wuJie/apps.ts
export interface PreloadAppType {
name: string; // 应用名称
hideSidebar?: boolean; // 是否隐藏侧边栏
customProps?: Record<string, any>; // 自定义 props
keepAlive?: boolean; // 是否保持存活
url?: string; // 应用 URL
path?: string; // 路径
exec?: boolean; // 是否执行 JS
degrade?: boolean; // 是否降级
props?: Record<string, any>; // 注入数据
isPreload?: boolean; // 是否预加载
}
const wujieApps: PreloadAppType[] = [
{
name: 'xxlJob',
isPreload: false,
path: '',
},
{
name: 'bi',
isPreload: false,
path: '/panel/index',
},
];配置获取
// src/utils/wuJie/config.ts
import { wujieApps } from './apps';
export const getWujieContainerProps = (appName: string): PreloadAppType => {
const currentApp = wujieApps.find((app) => app.name === appName) || defaultApp;
return currentApp;
};使用方式
WujieContainer 组件
项目封装了 WujieContainer 组件:
<template>
<WujieVue
:alive="wujieProps.keepAlive"
:degrade="false"
:name="appName"
:plugins="plugins"
:props="propsData"
:url="appUrl"
:fetch="customFetch"
:sync="true"
:fiber="true"
height="100vh"
width="100%"
@load-error="handleError"
/>
</template>
<script setup lang="ts">
import { useAppConfig } from '@/hooks/setting';
import { getWujieContainerProps } from '@/utils/wuJie/config';
import { plugins } from '@/utils/wuJie/plugins';
import WujieVue from 'wujie-vue3';
const config = useAppConfig();
// 根据路由获取应用名称
const appName = computed(() => {
const segments = route.path.split('/').filter(Boolean);
return segments.length > 0 ? segments[0] : 'default';
});
// 获取应用配置
const wujieProps = getWujieContainerProps(appName.value);
// 构建完整 URL
const appUrl = computed(() => {
const wujieUrl = config.wujieUrl;
const subPath = route.path.slice(`/${appName.value}`.length) || '/';
return `${wujieUrl}/${appName.value}${subPath}`;
});
// 传递给子应用的数据
const propsData = computed(() => ({
data: {
hideSidebar: wujieProps.hideSidebar,
token: getToken(),
userInfo: userStore.getUserInfo,
},
methods: {
logout: () => userStore.logout(true),
getGlobalConfig: () => ({
apiUrl: config.apiUrl,
uploadUrl: config.uploadUrl,
}),
},
}));
// 自定义 fetch(带 token)
const customFetch = (url: string, options: RequestInit) => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000);
return fetch(url, {
...options,
signal: controller.signal,
headers: {
...options?.headers,
'X-Requested-With': 'XMLHttpRequest',
Authorization: `Bearer ${getToken()}`,
},
}).finally(() => clearTimeout(timeoutId));
});
</script>通信机制
主应用向子应用传递数据
// 通过 props 传递
const propsData = {
data: {
token: getToken(),
userInfo: userStore.getUserInfo,
},
methods: {
logout: () => userStore.logout(true),
},
};子应用向主应用通信
// 子应用发送
import WujieVue from 'wujie-vue3';
WujieVue.bus.$emit('biChange', {
type: 'router',
path: '/dashboard',
query: {},
});// 主应用监听
WujieVue.bus.$on('biChange', async (val) => {
if (val.type === 'logout') {
await userStore.logout();
}
if (val.type === 'router') {
router.push({
path: '/bi' + val.path,
query: val.query,
});
}
});主应用通知子应用路由变化
const adminRouteChange = (val: { path: string; query?: {} }) => {
WujieVue.bus.$emit('admin-router-change', {
path: val.path,
query: val.query,
});
};预加载策略
// src/utils/wuJie/preload.ts
import WujieVue from 'wujie-vue3';
import { wujieApps } from '@/utils/wuJie/apps';
import { checkSubAppHealth } from './healthCheck';
// 初始化预加载
export async function initPreloadApps() {
const preloadApps = wujieApps.filter((app) => app.isPreload);
const preloadQueue = preloadApps.map(async (app) => {
// 1. 健康检查
const healthResult = await checkSubAppHealth(app.url, {
timeout: 5000,
skipCheck: false,
});
// 2. 健康检查失败则跳过
if (!healthResult.healthy) {
console.warn(`[${app.name}] 健康检查失败,跳过预加载`);
return;
}
// 3. 执行预加载
await WujieVue.preloadApp({
name: app.name,
url: app.url,
exec: app.exec ?? true,
degrade: app.degrade ?? false,
props: app.props,
});
});
await Promise.allSettled(preloadQueue);
}保活模式
保活模式可以让子应用在切换时不销毁,保持状态:
<WujieVue
name="sub-app"
url="http://localhost:8080/"
:alive="true"
></WujieVue>生命周期钩子
// src/utils/wuJie/lifecycle.ts
export const createLifecycles = (options: {
appName: string;
loading: Ref<boolean>;
}): LifecycleHooks => {
return {
beforeLoad: (_appWindow: any) => {
console.log(`[${appName}] 开始加载`);
loading.value = true;
},
beforeMount: (_appWindow: any) => {
console.log(`[${appName}] 开始挂载`);
},
afterMount: (appWindow: any) => {
console.log(`[${appName}] 挂载完成`);
loading.value = false;
// 注入全局 API
appWindow.$wujie = {
sendToMain: (event: string, data: any) => {
window.$wujie.bus.$emit(`${appName}:${event}`, data);
},
getToken: () => getToken(),
};
},
beforeUnmount: (appWindow: any) => {
console.log(`[${appName}] 准备卸载`);
},
afterUnmount: (_appWindow: any) => {
console.log(`[${appName}] 已卸载`);
loading.value = false;
},
loadError: (url: string, e: Error) => {
console.error(`[${url}] 加载失败:`, e);
},
};
};常见问题
样式冲突
Wujie 使用 Shadow DOM 隔离,但仍需注意:
- 子应用避免使用全局样式
- 使用 scoped 或 CSS Modules
- 避免使用
body、html选择器
开发环境跨域
子应用开发服务器需要配置 CORS:
// vite.config.js
export default {
server: {
headers: {
'Access-Control-Allow-Origin': '*',
},
},
};路由同步
// 监听主应用路由变化,通知子应用
watch(
() => router.currentRoute.value.path,
(toPath) => {
const query = route.query || {};
handleRouteChange(toPath, query);
},
{ immediate: true, deep: true }
);相关链接
页面信息›
已优化是