import { lazy, Suspense, memo } from 'react' import { Routes, Route, Navigate } from 'react-router' import { Toaster } from '@/components/ui/sonner' import { LoadingSpinner } from '@/components/LoadingSpinner' // 路由守卫组件 - 独立定义,便于复用 const RequireAuth = memo(function RequireAuth({ children }: { children: React.ReactNode }) { const token = localStorage.getItem('token') if (!token) { return } // 动态导入Layout以避免在登录页面加载它 return {children} }) // 懒加载页面组件 - 实现代码分割 const Login = lazy(() => import('@/pages/Login')) const Dashboard = lazy(() => import('@/pages/Dashboard')) const Clusters = lazy(() => import('@/pages/Clusters')) const Hosts = lazy(() => import('@/pages/Hosts')) const Storage = lazy(() => import('@/pages/Storage')) const Deployments = lazy(() => import('@/pages/Deployments')) const Collectors = lazy(() => import('@/pages/Collectors')) const Settings = lazy(() => import('@/pages/Settings')) const Layout = lazy(() => import('@/components/Layout')) // 懒加载布局包装器 function LazyLayout({ children }: { children: React.ReactNode }) { return ( }> {children} ) } // 页面加载中占位 function PageLoadingFallback() { return (
) } // 路由配置 - 集中管理路由定义 interface RouteConfig { path: string element: React.ReactNode auth?: boolean } const routes: RouteConfig[] = [ { path: '/login', element: , auth: false }, { path: '/', element: , auth: true }, { path: '/clusters', element: , auth: true }, { path: '/hosts', element: , auth: true }, { path: '/storage', element: , auth: true }, { path: '/deployments', element: , auth: true }, { path: '/collectors', element: , auth: true }, { path: '/settings', element: , auth: true }, ] /** * App 根组件 * * 优化点: * 1. 所有页面使用 React.lazy 懒加载,实现代码分割 * 2. 路由守卫独立为 memo 组件 * 3. Suspense 统一处理加载状态 * 4. 路由配置集中管理 */ const App = memo(function App() { return ( <> {routes.map((route) => ( {route.element} ) : ( }> {route.element} ) } /> ))} } /> ) }) export default App