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

48 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-08-12 09:39:09 +00:00
import { RouteDto } from '@/proxy/routes/models'
2025-06-28 21:34:28 +00:00
import { lazy } from 'react'
// Tüm view bileşenlerini import et (vite özel)
// shared klasörü hariç, çünkü bu bileşenler genellikle başka yerlerde statik import ediliyor
const modules = import.meta.glob(['../views/**/*.tsx', '!../views/shared/**/*.tsx'])
2025-06-28 21:34:28 +00:00
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 {
2025-08-12 09:39:09 +00:00
key: string
path: string
getComponent: () => React.LazyExoticComponent<React.ComponentType<any>>
routeType: string
authority?: string[]
2025-06-28 21:34:28 +00:00
}
// 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,
2025-08-12 09:39:09 +00:00
}))
2025-06-28 21:34:28 +00:00
}