40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import { lazy, ComponentType } from 'react';
|
|
|
|
/**
|
|
* 使用 Vite 的 import.meta.glob 自动扫描所有页面组件
|
|
* 这样就不需要手动维护映射表了
|
|
*/
|
|
const modules = import.meta.glob<{ default: ComponentType<any> }>('/src/pages/**/index.tsx');
|
|
|
|
/**
|
|
* 根据 component 路径动态加载对应的组件
|
|
* @param componentPath 组件路径 (例如: 'Dashboard', 'Deploy/Application/List')
|
|
* @param suppressWarning 是否抑制警告(用于隐藏菜单等场景)
|
|
* @returns 懒加载的组件或 null
|
|
*/
|
|
export const getRouteComponent = (
|
|
componentPath: string | null | undefined,
|
|
suppressWarning: boolean = false
|
|
): React.LazyExoticComponent<ComponentType<any>> | null => {
|
|
if (!componentPath) return null;
|
|
|
|
// 移除开头和结尾的斜杠
|
|
const cleanPath = componentPath.replace(/^\/+|\/+$/g, '');
|
|
|
|
// 构建完整的模块路径
|
|
const modulePath = `/src/pages/${cleanPath}/index.tsx`;
|
|
|
|
// 检查模块是否存在
|
|
if (!modules[modulePath]) {
|
|
// 只在开发环境且未抑制警告时输出
|
|
if (import.meta.env.DEV && !suppressWarning) {
|
|
console.warn(`⚠️ 路由组件未找到: ${modulePath}`);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// 返回懒加载组件
|
|
return lazy(() => modules[modulePath]().then((m: { default: ComponentType<any> }) => ({ default: m.default })));
|
|
};
|
|
|