Created
May 3, 2022 20:00
-
-
Save bigujun/5bdb40c3fcedd5ca3e8e3c4e3dcc8541 to your computer and use it in GitHub Desktop.
Vite + React + React rotuer dom, route pages from /pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Fragment, lazy, Suspense } from 'react' | |
import { Routes, Route } from 'react-router-dom' | |
const PRESERVED = import.meta.globEager('/src/pages/(_app|404).tsx') | |
const ROUTES = import.meta.glob('/src/pages/**/[a-z[]*.tsx') | |
// const ROUTES = import.meta.globEager('/src/pages/**/[a-z[]*.tsx') | |
const preserved = Object.keys(PRESERVED).reduce((preserved, file) => { | |
const key = file.replace(/\/src\/pages\/|\.tsx$/g, '') | |
return { ...preserved, [key]: PRESERVED[file].default } | |
}, {}) as Record<string, typeof Fragment> | |
const routes = Object.keys(ROUTES).map((route) => { | |
const path = route | |
.replace(/\/src\/pages|index|\.tsx$/g, '') | |
.replace(/\[\.{3}.+\]/, '*') | |
.replace(/\[(.+)\]/, ':$1') | |
return { path, component: lazy(ROUTES[route] as any) } | |
}) | |
export const Router = () => { | |
const App = preserved?.['_app'] || Fragment | |
const NotFound = preserved?.['404'] || Fragment | |
return ( | |
<App> | |
<Suspense fallback={'Loading...'}> | |
<Routes> | |
{routes.map(({ path, component: Component = Fragment }) => ( | |
<Route key={path} path={path} element={<Component/>} /> | |
))} | |
<Route path="*" element={<NotFound />} /> | |
</Routes> | |
</Suspense> | |
</App> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment