### Install React Router Auto Routes Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Install the library as a dev dependency using npm. ```bash npm install -D react-router-auto-routes ``` -------------------------------- ### Custom autoRoutes Configuration Example Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Example demonstrating how to customize `autoRoutes` behavior using `routesDir` for multiple route directories and `visitFiles` for custom file discovery, useful for testing or virtual filesystems. ```javascript // Example: custom visitFiles for testing or virtual filesystems const routes: RouteConfig[] = autoRoutes({ routesDir: { '/': 'app/routes', '/admin': 'admin/routes' }, visitFiles: (dir, visitor) => { if (dir.endsWith('app/routes')) { visitor('index.tsx') visitor('dashboard/_layout.tsx') visitor('dashboard/index.tsx') } if (dir.endsWith('admin/routes')) { visitor('users.tsx') } }, }) // routes[0] → { id: 'routes/index', file: 'routes/index.tsx', index: true } // routes[1] → { id: 'routes/dashboard/_layout', file: '...', path: 'dashboard', children: [...] } ``` -------------------------------- ### Basic App Setup with Auto Routes Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Import and use the autoRoutes function in your app's route configuration file. ```typescript import { autoRoutes } from 'react-router-auto-routes' export default autoRoutes() ``` -------------------------------- ### CLI Migration for auto-routes Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Run the migration CLI to update projects from remix-flat-routes. Ensure TypeScript 5.0+ is installed as the CLI resolves the compiler from your workspace. ```bash npx migrate-auto-routes ``` -------------------------------- ### Colocation with '+' Prefix Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Use files and folders starting with '+' to colocate non-route assets like helpers, types, and components next to their corresponding routes. These are ignored by the router. ```treeview routes/ ├── dashboard/ │ ├── _layout.tsx → Route: layout for /dashboard/* │ ├── index.tsx → Route: /dashboard │ ├── +/ → Anonymous colocated folder (ignored by router) │ │ ├── helpers.ts │ │ └── types.ts │ └── +components/ → Named colocated folder (ignored by router) │ └── data-table.tsx └── users/ ├── index.tsx → Route: /users ├── +user-list.tsx → Colocated file (ignored by router) └── $id/ ├── index.tsx → Route: /users/:id ├── edit.tsx → Route: /users/:id/edit └── +/ ├── query.ts └── validation.ts ``` -------------------------------- ### Routing File Conventions Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Illustrates how filenames and folder structures map to URL segments, including index routes, dynamic segments, optional segments, pathless groups, and catch-all routes. ```plaintext routes/ ├── index.tsx → / (index route) ├── about.tsx → /about ├── robots[.]txt.ts → /robots.txt (literal dot via escape) ├── (en)/about.tsx → /en?/about (optional segment) ├── ($lang)/home.tsx → /:lang?/home (optional dynamic segment) ├── _auth/ → pathless group (no /auth in URL) │ ├── _layout.tsx → shared auth layout │ ├── login.tsx → /login │ └── signup.tsx → /signup ├── blog/ │ ├── _layout.tsx → layout for /blog/* │ ├── index.tsx → /blog │ ├── $slug.tsx → /blog/:slug │ └── archive.tsx → /blog/archive └── files/ └── $.tsx → /files/* (splat / catch-all) # Equivalent flat (dot-delimited) versions: # _auth._layout.tsx _auth.login.tsx blog._layout.tsx blog.$slug.tsx files.$.tsx ``` -------------------------------- ### Run CLI to Migrate Routes Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Use this command to migrate routes from a source directory to a target directory. The CLI includes safety checks and handles staging and swapping of routes. ```bash npx migrate-auto-routes app/routes app/new-routes ``` -------------------------------- ### Configure autoRoutes with basic options Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Set up autoRoutes with a specific routes directory and custom ignored files. The `paramChar` and `colocationChar` can be customized for route definition. ```typescript autoRoutes({ routesDir: 'routes', ignoredRouteFiles: ['**/.*'], // Ignore dotfiles like .gitkeep paramChar: '$', colocationChar: '+', routeRegex: /\.(ts|tsx|js|jsx|md|mdx)$/, }) ``` -------------------------------- ### Flat (Dot-Delimited) Routing Convention Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Demonstrates the equivalent flat file structure using dot-delimited notation for defining routes. ```treeview routes/ ├── index.tsx → / (index route) ├── about.tsx → /about ├── robots[.]txt.ts → /robots.txt (literal dot segment) ├── _auth._layout.tsx → Auth layout ├── _auth.login.tsx → /login ├── _auth.signup.tsx → /signup ├── blog._layout.tsx → Layout for /blog/* routes ├── blog.index.tsx → /blog ├── blog.$slug.tsx → /blog/:slug (dynamic param) ├── blog.archive.tsx → /blog/archive ├── dashboard._layout.tsx → Layout for dashboard routes ├── dashboard.index.tsx → /dashboard ├── dashboard.analytics.tsx → /dashboard/analytics ├── dashboard.settings._layout.tsx → Layout for settings routes ├── dashboard.settings.index.tsx → /dashboard/settings ├── dashboard.settings.profile.tsx → /dashboard/settings/profile └── files.$.tsx → /files/* (splat - catch-all) ``` -------------------------------- ### Importing Colocated Files Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Demonstrates how to import helper files that are colocated with route definitions using a '+' prefix. Ensure that '+' prefixed files and folders are not at the root level of the routes directory. ```typescript import { formatDate } from './+/helpers' ``` -------------------------------- ### Configure autoRoutes for Monorepo with multiple route roots Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Mount filesystem folders to specific URL paths for organizing sub-apps or monorepo packages. Folder paths resolve from the project root. ```typescript autoRoutes({ routesDir: { '/': 'app/routes', '/api': 'api/routes', '/docs': 'packages/docs/routes', '/shop': 'packages/shop/routes', }, }) ``` -------------------------------- ### migrate-auto-routes CLI Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Command-line interface for automating the migration to react-router-auto-routes. It wraps the `migrate()` function with git safety checks, snapshot diffing, automatic swap/rollback, and optional legacy route file rewriting. ```APIDOC ## migrate-auto-routes CLI — Automated safe migration workflow The CLI wraps `migrate()` with git safety checks, a `npx react-router routes` snapshot diff, automatic swap/rollback, and optional legacy `app/routes.ts` rewriting. ```bash # Default: reads from app/routes, writes staged result to app/new-routes npx migrate-auto-routes # Explicit source and target npx migrate-auto-routes app/routes app/new-routes # Dry run — generates new routes but does NOT swap them into place npx migrate-auto-routes --dry-run # What the CLI does automatically: # 1. Verifies you are inside a git repository # 2. Checks that app/routes has no uncommitted changes (clean worktree) # 3. Runs `npx react-router routes` to capture a BEFORE snapshot # 4. Calls migrate() to produce the new routes in app/new-routes # 5. Renames app/routes → app/old-routes, moves app/new-routes → app/routes # 6. If app/routes.ts still uses createRoutesFromFolders, rewrites it to autoRoutes() # 7. Runs `npx react-router routes` again for an AFTER snapshot # 8. If snapshots match → removes backup, prints ✅ ``` ``` -------------------------------- ### migrate(sourceDir, targetDir, options?) Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Programmatic migration API to convert a remix-flat-routes directory structure to the react-router-auto-routes colocation convention. It scans route files, computes target paths, copies colocated assets into '+' prefixed folders, and rewrites import specifiers. ```APIDOC ## migrate(sourceDir, targetDir, options?) — Programmatic migration API Converts a `remix-flat-routes` directory tree to the `react-router-auto-routes` `+` colocation convention. Scans every route file, applies `convertToRoute()` to compute the target flat path, and copies colocated assets into `+` prefixed folders. Import specifiers inside all `.ts`/`.tsx`/`.js`/`.jsx` files are rewritten using the TypeScript compiler API. ```typescript import { migrate } from 'react-router-auto-routes/migration' // Basic migration migrate('app/routes', 'app/new-routes') // With options migrate('app/routes', 'app/new-routes', { force: true, // overwrite target if it exists ignoredRouteFiles: ['**/*.css'], // skip non-route files not using + prefix }) // What it does: // 1. Scans sourceDir with remix-flat-routes semantics // 2. For each route, computes a flat target path via convertToRoute() // e.g. users/$id/route.tsx → users/$id/_layout.tsx (if it has children) // users/$id/edit.tsx → users/$id/edit.tsx // 3. Colocated files (non-route assets) are moved into +/ folders // e.g. users/$id/avatar.png → users/$id/+/avatar.png // 4. All import specifiers in .ts/.tsx files are updated to reflect new paths // 5. Logs progress and emits '🏁 Finished!' on success ``` ``` -------------------------------- ### Route Ordering Rules for URL Matching Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Understand the priority rules used by `buildRouteTree` to sort routes when multiple matches are possible. This is crucial for diagnosing unexpected route behavior. ```typescript import { autoRoutes } from 'react-router-auto-routes' // Given this file structure: // routes/ // $id/root.tsx → /:id/root // root/$id.tsx → /root/$id const routes = autoRoutes() // Sorted order (static prefix wins over dynamic prefix at same depth): // routes[0] → { id: 'routes/root/$id', path: 'root/:id' } ← static first segment // routes[1] → { id: 'routes/$id/root', path: ':id/root' } ← dynamic first segment // Full priority rules applied by sortForAssembly(): // 1. Fewer path segments first (/about before /about/team) // 2. Non-index routes before index routes // 3. Layout routes (_layout.tsx) before regular routes // 4. More specific paths first: static(4) > optional-static(3) > required-param(2) > optional-param(1) > splat(0) // 5. Alphabetical by route id as final tiebreaker ``` -------------------------------- ### Uninstall Legacy Packages Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md After successfully migrating routes, uninstall the old packages to clean up your project dependencies. ```bash npm uninstall remix-flat-routes npm uninstall @react-router/remix-routes-option-adapter ``` -------------------------------- ### Folder-Based Routing Convention Source: https://github.com/kenn/react-router-auto-routes/blob/main/README.md Illustrates the folder-based structure for defining routes, including index routes, layouts, dynamic segments, and splat routes. ```treeview routes/ ├── index.tsx → / (index route) ├── about.tsx → /about ├── robots[.]txt.ts → /robots.txt (literal dot segment) ├── _auth/ → Pathless layout (no /auth in URL) │ ├── _layout.tsx → Auth layout │ ├── login.tsx → /login │ └── signup.tsx → /signup ├── blog/ │ ├── _layout.tsx → Layout for /blog/* routes │ ├── index.tsx → /blog │ ├── $slug.tsx → /blog/:slug (dynamic param) │ └── archive.tsx → /blog/archive ├── dashboard/ │ ├── _layout.tsx → Layout for dashboard routes │ ├── index.tsx → /dashboard │ ├── analytics.tsx → /dashboard/analytics │ └── settings/ │ ├── _layout.tsx → Layout for settings routes │ ├── index.tsx → /dashboard/settings │ └── profile.tsx → /dashboard/settings/profile └── files/ └── $.tsx → /files/* (splat - catch-all) ``` -------------------------------- ### Monorepo / Multi-root Mounting with autoRoutes Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Configure `autoRoutes` with a `routesDir` object to mount different route directories at specific URL paths, suitable for monorepos or multi-root applications. ```typescript // app/routes.ts import { autoRoutes } from 'react-router-auto-routes' export default autoRoutes({ routesDir: { '/': 'app/routes', '/api': 'api/routes', '/docs': 'packages/docs/routes', '/shop': 'packages/shop/routes', }, }) ``` ```plaintext // Resulting paths (examples): // app/routes/dashboard.tsx → /dashboard // api/routes/users/index.tsx → /api/users (index: true) // api/routes/users/_layout.tsx → layout for /api/users/* // packages/docs/routes/index.tsx → /docs // packages/shop/routes/products.tsx → /shop/products ``` -------------------------------- ### migrate-auto-routes CLI Usage Source: https://context7.com/kenn/react-router-auto-routes/llms.txt The `migrate-auto-routes` CLI provides an automated workflow for migrating to `react-router-auto-routes`, including git safety checks, snapshot diffing, and optional rollback. ```bash # Default: reads from app/routes, writes staged result to app/new-routes npx migrate-auto-routes # Explicit source and target npx migrate-auto-routes app/routes app/new-routes # Dry run — generates new routes but does NOT swap them into place npx migrate-auto-routes --dry-run # What the CLI does automatically: # 1. Verifies you are inside a git repository # 2. Checks that app/routes has no uncommitted changes (clean worktree) # 3. Runs `npx react-router routes` to capture a BEFORE snapshot # 4. Calls migrate() to produce the new routes in app/new-routes # 5. Renames app/routes → app/old-routes, moves app/new-routes → app/routes # 6. If app/routes.ts still uses createRoutesFromFolders, rewrites it to autoRoutes() # 7. Runs `npx react-router routes` again for an AFTER snapshot # 8. If snapshots match → removes backup, prints ✅ ``` -------------------------------- ### autoRoutes() Configuration Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Configures and generates the route tree for the application. Supports overriding the app directory for non-standard project structures. ```APIDOC ## autoRoutes() ### Description Generates the route tree for the application based on the file structure. Can be configured with `routesDir` and `globalThis.__reactRouterAppDirectory`. ### Parameters #### Request Body - **routesDir** (Record) - Optional - A mapping of URL prefixes to route directories. ### Global Configuration - **globalThis.__reactRouterAppDirectory** (string) - Optional - Overrides the base directory for computing import prefixes when the `app/` folder is not at the project root. ### Request Example ```ts // vite.config.ts (or any server-side bootstrap) import path from 'path' import { autoRoutes } from 'react-router-auto-routes' ;(globalThis as any).__reactRouterAppDirectory = path.resolve( process.cwd(), 'app/router', ) // app/router/routes.ts import { autoRoutes } from 'react-router-auto-routes' export default autoRoutes({ routesDir: { '/shop': 'shop/routes' }, }) // import prefix for shop/routes/index.tsx → '../../shop/routes/index.tsx' // (resolved relative to app/router/, not app/) ``` ``` -------------------------------- ### Programmatic Migration API Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Use the `migrate` function to programmatically convert a `remix-flat-routes` directory structure to the `react-router-auto-routes` colocation convention. It handles file copying, folder creation, and import specifier rewriting. ```typescript import { migrate } from 'react-router-auto-routes/migration' // Basic migration migrate('app/routes', 'app/new-routes') // With options migrate('app/routes', 'app/new-routes', { force: true, // overwrite target if it exists ignoredRouteFiles: ['**/*.css'], // skip non-route files not using + prefix }) // What it does: // 1. Scans sourceDir with remix-flat-routes semantics // 2. For each route, computes a flat target path via convertToRoute() // e.g. users/$id/route.tsx → users/$id/_layout.tsx (if it has children) // users/$id/edit.tsx → users/$id/edit.tsx // 3. Colocated files (non-route assets) are moved into +/ folders // e.g. users/$id/avatar.png → users/$id/+/avatar.png // 4. All import specifiers in .ts/.tsx files are updated to reflect new paths // 5. Logs progress and emits '🏁 Finished!' on success ``` -------------------------------- ### Importing Colocated Files Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Import colocated files directly from within a route module using their relative paths. The router ignores files and folders prefixed with '+'. ```javascript import { formatDate } from './+/helpers' import { DataTable } from './+components/data-table' import { userListSchema } from './+user-list' ``` -------------------------------- ### Generate Route Config with autoRoutes Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Use the `autoRoutes` function to generate a route configuration. It can be used with zero configuration or with various options to customize directory scanning, file matching, and segment naming. ```typescript // app/routes.ts import { autoRoutes } from 'react-router-auto-routes' // Zero-config: reads from app/routes/ export default autoRoutes() // With full options export default autoRoutes({ routesDir: 'routes', // string path relative to app/ ignoredRouteFiles: ['**/.*'], // glob patterns to skip (dotfiles, etc.) paramChar: '$', // prefix for dynamic segments ($id → :id) colocationChar: '+', // prefix for colocated non-route files routeRegex: /\.(ts|tsx|js|jsx|md|mdx)$/, // override file detection regex }) ``` ```typescript // Expected output shape (RouteConfig[]): // [ // { id: 'routes/_layout', file: 'routes/_layout.tsx' }, // { id: 'routes/index', file: 'routes/index.tsx', index: true, parentId: 'routes/_layout' }, // { id: 'routes/about', file: 'routes/about.tsx', path: 'about', parentId: 'routes/_layout' }, // { id: 'routes/blog/$slug', file: 'routes/blog/$slug.tsx', path: ':slug', parentId: '...' }, // ] ``` -------------------------------- ### isRouteModuleFile(filename, colocationChar?, routeRegex?) Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Determines if a file should be registered as a route module. This function is useful for custom file visitation logic and testing. ```APIDOC ## isRouteModuleFile(filename, colocationChar?, routeRegex?) ### Description Returns `true` if a given relative file path should be registered as a route module. Used internally by `collectRouteInfos()` but also exported for custom `visitFiles` implementations and testing. ### Parameters #### Path Parameters - **filename** (string) - Required - The relative path of the file to check. - **colocationChar** (string) - Optional - The character used for colocation (default is '+'). - **routeRegex** (RegExp) - Optional - A regular expression to filter route files. ### Request Example ```ts import { isRouteModuleFile } from 'react-router-auto-routes' // Standard route files isRouteModuleFile('index.tsx') // true isRouteModuleFile('dashboard/_layout.tsx') // true isRouteModuleFile('blog/$slug.tsx') // true isRouteModuleFile('api/users/route.ts') // true // Colocated files (+ prefix) — always false isRouteModuleFile('+helpers.ts') // throws (must be inside route folder) isRouteModuleFile('dashboard/+helpers.ts') // false isRouteModuleFile('dashboard/+/utils.ts') // false // Server-only files — always false isRouteModuleFile('dashboard/db.server.ts') // false // Custom colocation char isRouteModuleFile('dashboard/@helpers.ts', '@') // false (colocated) isRouteModuleFile('dashboard/index.tsx', '@') // true // Custom route regex (e.g. restrict to .tsx only) const tsxOnly = /\.(tsx)$/ isRouteModuleFile('about.ts', '+', tsxOnly) // false isRouteModuleFile('about.tsx', '+', tsxOnly) // true ``` ``` -------------------------------- ### Override App Directory with globalThis.__reactRouterAppDirectory Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Set the global `__reactRouterAppDirectory` variable before calling `autoRoutes()` to specify a non-root application directory. This is useful when your `app/` folder is nested within the project. ```typescript // vite.config.ts (or any server-side bootstrap) import path from 'path' import { autoRoutes } from 'react-router-auto-routes' ;(globalThis as any).__reactRouterAppDirectory = path.resolve( process.cwd(), 'app/router', ) // app/router/routes.ts import { autoRoutes } from 'react-router-auto-routes' export default autoRoutes({ routesDir: { '/shop': 'shop/routes' }, }) // import prefix for shop/routes/index.tsx → '../../shop/routes/index.tsx' // (resolved relative to app/router/, not app/) ``` -------------------------------- ### Classify Route Module Files with isRouteModuleFile Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Use `isRouteModuleFile` to determine if a file should be registered as a route. It handles standard route files, colocated files with the '+' prefix, and server-only files. Custom colocation characters and route regular expressions can also be provided. ```typescript import { isRouteModuleFile } from 'react-router-auto-routes' // Standard route files isRouteModuleFile('index.tsx') // true isRouteModuleFile('dashboard/_layout.tsx') // true isRouteModuleFile('blog/$slug.tsx') // true isRouteModuleFile('api/users/route.ts') // true // Colocated files (+ prefix) — always false isRouteModuleFile('+helpers.ts') // throws (must be inside route folder) isRouteModuleFile('dashboard/+helpers.ts') // false isRouteModuleFile('dashboard/+/utils.ts') // false // Server-only files — always false isRouteModuleFile('dashboard/db.server.ts') // false // Custom colocation char isRouteModuleFile('dashboard/@helpers.ts', '@') // false (colocated) isRouteModuleFile('dashboard/index.tsx', '@') // true // Custom route regex (e.g. restrict to .tsx only) const tsxOnly = /\.(tsx)$/ isRouteModuleFile('about.ts', '+', tsxOnly) // false isRouteModuleFile('about.tsx', '+', tsxOnly) // true ``` -------------------------------- ### autoRoutesOptions and RouteConfig Types Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Defines the TypeScript types for `autoRoutesOptions` used to configure route generation and `RouteConfig` which represents the structure of generated routes. ```typescript import type { autoRoutesOptions, RouteConfig } from 'react-router-auto-routes' // autoRoutesOptions shape: type autoRoutesOptions = { routesDir?: string | Record visitFiles?: (dir: string, visitor: (file: string) => void) => void paramChar?: string // default: '$' colocationChar?: string // default: '+' ignoredRouteFiles?: readonly string[] // picomatch glob patterns routeRegex?: RegExp // override file discovery regex } // RouteConfig shape returned by autoRoutes(): type RouteConfig = { id: string file: string path?: string index?: boolean children?: RouteConfig[] } ``` -------------------------------- ### autoRoutesOptions Type Reference Source: https://context7.com/kenn/react-router-auto-routes/llms.txt Defines the TypeScript type for options accepted by the autoRoutes() function, including directory configuration, file visiting, and character settings for parameters and colocation. ```APIDOC ## autoRoutesOptions — TypeScript type reference Full type definition for the options accepted by `autoRoutes()`. ```typescript import type { autoRoutesOptions, RouteConfig } from 'react-router-auto-routes' // autoRoutesOptions shape: type autoRoutesOptions = { routesDir?: string | Record visitFiles?: (dir: string, visitor: (file: string) => void) => void paramChar?: string // default: '$' colocationChar?: string // default: '+' ignoredRouteFiles?: readonly string[] // picomatch glob patterns routeRegex?: RegExp // override file discovery regex } // RouteConfig shape returned by autoRoutes(): type RouteConfig = { id: string file: string path?: string index?: boolean children?: RouteConfig[] } // Example: custom visitFiles for testing or virtual filesystems const routes: RouteConfig[] = autoRoutes({ routesDir: { '/': 'app/routes', '/admin': 'admin/routes' }, visitFiles: (dir, visitor) => { if (dir.endsWith('app/routes')) { visitor('index.tsx') visitor('dashboard/_layout.tsx') visitor('dashboard/index.tsx') } if (dir.endsWith('admin/routes')) { visitor('users.tsx') } }, }) // routes[0] → { id: 'routes/index', file: 'routes/index.tsx', index: true } // routes[1] → { id: 'routes/dashboard/_layout', file: '...', path: 'dashboard', children: [...] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.