index.ts 2.19 KB
import {
  addGlobalUncaughtErrorHandler,
  registerMicroApps,
  start,
} from 'qiankun';

import { microApps } from './apps'; // 微应用信息配置
import { communicationManager } from './communication'; // 通信管理器
import { microAppLifecycles } from './lifecycles'; // 微应用生命周期钩子

/**
 * qiankun 配置选项
 */
const qiankunConfig = {
  // 预加载策略:改为 false,避免在容器未就绪时预加载导致的问题
  // 刷新页面时,先让当前路由的微应用正常加载,再进行预加载
  prefetch: false,

  // 沙箱配置
  sandbox: {
    // 是否开启严格样式隔离(Shadow DOM)
    strictStyleIsolation: false,
    // 是否开启实验性样式隔离(scoped css)
    experimentalStyleIsolation: true,
  },

  // 单例模式:同一时间只能有一个微应用在运行
  singular: true,

  // 获取公共资源的方式
  // fetch: customFetch,

  // 在第一个微应用加载后再开启预加载
  // 这样可以避免刷新时的竞态条件
};

/**
 * 初始化并启动 qiankun
 */
export function setupQiankun() {
  // 1. 初始化通信管理器
  communicationManager.init();
  registerMicroApps(microApps, microAppLifecycles);

  // 3. 添加全局错误处理
  addGlobalUncaughtErrorHandler((event) => {
    // 可以在这里做一些全局错误处理
    // 例如:错误上报、错误提示等
    const { message } = event as any;
    if (message && message.includes('died in status')) {
      console.error('[qiankun] 微应用加载失败,请检查微应用是否正常运行');
    }
  });

  // 4. 启动 qiankun
  start(qiankunConfig);
}

/**
 * 导出相关模块,方便外部使用
 */
export {
  getMicroAppByPath,
  getMicroAppConfig,
  getMicroAppNames,
  isMicroAppRegistered,
  microApps,
} from './apps';
export { broadcast, communicationManager } from './communication';
export type { GlobalState, Notification } from './communication';
export { microAppLifecycles } from './lifecycles';
// 导出子应用适配器相关类型和函数
export { createSubAppAdapter } from './subAppAdapter';
export type { QiankunProps, SubAppCommunicationManager } from './subAppAdapter';
export * from './types';
export * from './utils';