Skip to content

Instantly share code, notes, and snippets.

@richkevan
Created September 16, 2023 04:52
Show Gist options
  • Save richkevan/27c3e59f653ea88408427cc4003a0a3f to your computer and use it in GitHub Desktop.
Save richkevan/27c3e59f653ea88408427cc4003a0a3f to your computer and use it in GitHub Desktop.
Dynamic File Router for React Apps
// src/routes.tsx
const ROUTES: {[key: string]: {default: any}} = import.meta.glob('/src/pages/**/[a-z[]*.tsx', { eager: true })
console.log("ROUTES",ROUTES)
const routes: {path: any, element: any}[] = Object.keys(ROUTES).map((route: any) => {
const path = route
.replace(/\/src\/pages|index|\.tsx$/g, '')
.replace(/\[\.{3}.+\]/, '*')
.replace(/\[(.+)\]/, ':$1')
console.log("path", path)
return { path, element: ROUTES[route].default }
})
console.log("routes.tsx", routes)
export default routes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment