UNPKG

file-router-react

Version:

File-based routing for React using wouter.

102 lines (75 loc) 2.5 kB
# file-router-react A file-based routing library for React using [wouter](https://github.com/molefrog/wouter). ## Features - Automatically generates routes from `src/pages` directory - Dynamic route support (`[id].tsx``/:id`) - Integrates with [wouter](https://github.com/molefrog/wouter) - TypeScript support - Works with both Webpack and Vite ## Installation ```bash npm install file-router-react wouter ``` ## Usage ### Option 1: Automatic File-Based Routing (Recommended) 1. **Create your pages structure:** ``` src/pages/ ├── index.tsx (/ route) ├── about.tsx (/about route) ├── [id].tsx (/:id route) └── users/ ├── index.tsx (/users route) └── [id].tsx (/users/:id route) ``` 2. **Use in your app:** ```tsx import { FileRouter } from 'file-router-react'; function App() { return <FileRouter />; } ``` ### Option 2: Manual Route Configuration If automatic file detection doesn't work in your environment, you can manually define routes: ```tsx import { FileRouter } from 'file-router-react'; import HomePage from './pages/index'; import AboutPage from './pages/about'; import UserPage from './pages/[id]'; const routes = [ { path: '/', component: HomePage }, { path: '/about', component: AboutPage }, { path: '/users/:id', component: UserPage }, ]; function App() { return <FileRouter routes={routes} />; } ``` ## File Naming Conventions - `index.tsx``/` (root route) - `about.tsx``/about` - `[id].tsx``/:id` (dynamic route) - `users/[id].tsx``/users/:id` ## Example Page Component ```tsx // src/pages/[id].tsx import { useParams } from 'wouter'; export default function UserPage() { const { id } = useParams(); return ( <div> <h1>User: {id}</h1> </div> ); } ``` ## Troubleshooting If automatic file detection doesn't work: 1. Make sure your bundler supports `require.context` (Webpack) or `import.meta.glob` (Vite) 2. Ensure your pages are in `src/pages/` directory 3. Use manual route configuration as shown in Option 2 above ## Development This package automatically detects your bundler environment and uses the appropriate method for importing files: - **Webpack**: Uses `require.context` - **Vite**: Uses `import.meta.glob` - **Other/Fallback**: Use manual route configuration