Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bigujun/5bdb40c3fcedd5ca3e8e3c4e3dcc8541 to your computer and use it in GitHub Desktop.
Save bigujun/5bdb40c3fcedd5ca3e8e3c4e3dcc8541 to your computer and use it in GitHub Desktop.
Vite + React + React rotuer dom, route pages from /pages
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