import { createBrowserRouter, Navigate, useLocation, Outlet } from 'react-router-dom'; import { lazy, Suspense } from 'react'; import LoadingSpinner from './components/LoadingSpinner'; // 懒加载组件 const Home = lazy(() => import('./pages/Home')); const Daily = lazy(() => import('./pages/Daily')); const Article = lazy(() => import('./pages/Article')); const AdminLayout = lazy(() => import('./pages/admin/layout/AdminLayout')); const Login = lazy(() => import('./pages/admin/login')); const Header = lazy(() => import('./components/layout/Header')); const Footer = lazy(() => import('./components/Footer')); // 管理页面组件 const Dashboard = lazy(() => import('./pages/admin/dashboard/Dashboard')); const PostsManagement = lazy(() => import('./pages/admin/posts/PostsManagement')); const PostEditor = lazy(() => import('./pages/admin/posts/PostEditor')); const DailyManagement = lazy(() => import('./pages/admin/daily/DailyManagement')); const MediasManagement = lazy(() => import('./pages/admin/medias/MediasManagement')); const CategoriesManagement = lazy(() => import('./pages/admin/categories/CategoriesManagement')); const UsersManagement = lazy(() => import('./pages/admin/users/UsersManagement')); const ContributorsManagement = lazy(() => import('./pages/admin/contributors/ContributorsManagement')); const Settings = lazy(() => import('./pages/admin/settings/Settings')); // 检查是否已登录 const checkAuth = () => { const token = localStorage.getItem('token'); console.debug('[Auth] Token exists:', !!token); return !!token; }; // 受保护的路由组件 const ProtectedRoute = ({ children }: { children: React.ReactNode }) => { const location = useLocation(); const isAuthenticated = checkAuth(); console.debug('[Router] Current location:', location.pathname); console.debug('[Router] Is authenticated:', isAuthenticated); if (!isAuthenticated) { console.debug('[Router] Redirecting to login'); return ; } return <>{children}; }; // 登录路由组件 const LoginRoute = () => { const isAuthenticated = checkAuth(); console.debug('[Login] Checking auth status'); if (isAuthenticated) { console.debug('[Login] Already authenticated, redirecting to admin'); return ; } return ( }> ); }; // 页面布局组件 const PageLayout = () => (
}>
); const router = createBrowserRouter([ { path: '/', element: ( }> ), children: [ { index: true, element: ( }> ), }, { path: 'daily', element: ( }> ), }, { path: 'posts/:articleId', element: ( }>
), }, ], }, { path: '/admin', children: [ { path: 'login', element: , }, { path: '', element: ( }> ), children: [ { index: true, element: ( }> ), }, { path: 'posts', children: [ { index: true, element: ( }> ), }, { path: 'new', element: ( }> ), }, { path: ':postId', element: ( }> ), }, ], }, { path: 'daily', element: ( }> ), }, { path: 'medias', element: ( }> ), }, { path: 'categories', element: ( }> ), }, { path: 'users', element: ( }> ), }, { path: 'contributors', element: ( }> ), }, { path: 'settings', element: ( }> ), }, ], }, ], }, { path: '*', element: , }, ]); export default router;