erp-platform/ui/src/routes/dynamicRouteLoader.tsx

47 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-06-28 21:34:28 +00:00
import { RouteDto } from '@/proxy/routes'
import { lazy } from 'react'
// Tüm view bileşenlerini import et (vite özel)
const modules = import.meta.glob('../views/**/*.tsx')
const lazyComponentCache = new Map<string, React.LazyExoticComponent<React.ComponentType<any>>>()
export function loadComponent(componentPath: string) {
const cleanedPath = componentPath.replace(/^@\//, '')
const fullPath = `../${cleanedPath}.tsx`
if (lazyComponentCache.has(fullPath)) {
return lazyComponentCache.get(fullPath)!
}
const loader = modules[fullPath]
if (!loader) {
console.error(`Component not found for path: ${fullPath}`)
throw new Error(`Component not found for path: ${fullPath}`)
}
const LazyComponent = lazy(loader as () => Promise<{ default: React.ComponentType<any> }>)
lazyComponentCache.set(fullPath, LazyComponent)
return LazyComponent
}
// React Router için uygun bir route tipi
export interface DynamicReactRoute {
key: string;
path: string;
getComponent: () => React.LazyExoticComponent<React.ComponentType<any>>;
routeType: string;
authority?: string[];
}
// API'den gelen route objesini, React Router için uygun hale getirir
export function mapDynamicRoutes(routes: RouteDto[]): DynamicReactRoute[] {
return routes.map((route) => ({
key: route.path,
path: route.path,
getComponent: () => loadComponent(route.componentPath),
routeType: route.routeType,
authority: route.authority,
}));
}