react-router-routepathgen
v0.1.0-alpha.1
Published
Generate route file paths based on route module names for React Router apps
Maintainers
Readme
🔁 rrv7-routegen
File-based route helper generator for React Router v7 - Automatically generate type-safe route helpers based on your file structure.
// Generated helper for type-safe route references
import { routeFile } from ".routegen/route-file";
// Usage in route configuration
route("/comments", routeFile("comments")); // ✅ Type-safe✨ Features
- 🗂️ Automatic Route Detection: Scans
app/routesfor React Router v7 route modules (withaction,loader, or default component exports). - 🛡️ Type-Safe Helpers: Generates a
routeFile()function with aRouteFilePathtype for compile-time safety. - ⚡️ Watch Mode: Real-time updates when route files are added, modified, or removed.
- 🔧 Configurable: Customize input/output directories and file names via CLI flags, a
routegen.config/jsfile, or Vite config. - 📦 Zero Config Default: Works out of the box with sensible defaults.
- 🔄 Nested Routes: Supports nested directory structures with slash notation (e.g.,
comments/indexx→comments/index). - 🧩 JavaScript & TypeScript: Compatible with
.js,.jsx, ``, andxfiles. - 🚀 Runtime Agnostic: Runs on Node.js and Bun.
- ⚙️ Vite Integration: Available as a lightweight Vite plugin for seamless integration with Vite 5.x and 6.x projects.
- 💨 Smart Generation: Only regenerates files when routes have actually changed.
- 💬 Comment-Aware: Intelligently ignores commented-out route modules.
📦 Installation
As a CLI Tool
# Using npm
npm install rrv7-routegen --save-dev
# Using Bun
bun add rrv7-routegen --devAs a Vite Plugin
# Using npm
npm install rrv7-routegen --save-dev
# Using Bun
bun add rrv7-routegen --devNote: The Vite plugin requires vite (^5.0.0 or ^6.0.0) as a peer dependency.
For Local Development (Linking)
From the
rrv7-routegenproject root:# Build the package bun run build # Link globally bun linkIn your target project:
# Link the package bun link rrv7-routegen # Add to package.json bun add rrv7-routegen --dev
🚀 Usage
As a Vite Plugin
Integrate rrv7-routegen directly into your Vite project (requires Vite 5.x or 6.x) for automatic route generation during development and build.
Add the plugin to your Vite config:
// vite.config.js import { defineConfig } from 'vite'; import routegen from 'rrv7-routegen/vite'; export default defineConfig({ plugins: [ routegen({ routeDir: 'src/routes', outDir: 'generated', outputFileName: 'routes', }), ], });Optionally, use a
routegen.configorroutegen.config.jsfile for configuration (merged with Vite config options):// routegen.config import { routeConfig } from 'rrv7-routegen'; export default routeConfig({ routeDir: 'src/routes', outDir: 'generated', outputFileName: 'routes', });Run Vite:
viteThe plugin will generate the route file on server start and build start, and automatically update it when route files change in development mode.
As a CLI Tool
File Structure
The tool scans the app/routes directory by default for route modules.
app/
└── routes/
├── homex
├── comments/
│ ├── indexx
│ └── detailsx
└── settingsxCLI Commands
Generate the route file once:
bunx rrv7-routegen generate
# or
npx rrv7-routegen generateWatch for changes and regenerate automatically:
bunx rrv7-routegen watch
# or
npx rrv7-routegen watchDefault behavior (runs generate if no command is specified):
bunx rrv7-routegen
# or
npx rrv7-routegenCLI Options
Customize the tool's behavior with the following options:
| Option | Description | Default |
| --- | --- | --- |
| --route-dir <path> | Directory to scan for routes | app/routes |
| --out-dir <path> | Output directory for generated files | .routegen |
| --output-file-name <name> | Name of the generated route file | route-file |
Example with custom options:
bunx rrv7-routegen generate --route-dir src/routes --out-dir generated --output-file-name routesConfiguration File
You can configure the tool via a routegen.config or routegen.config.js file using the routeConfig function.
Example routegen.config:
import { routeConfig } from "rrv7-routegen";
export default routeConfig({
routeDir: "src/routes",
outDir: "generated",
outputFileName: "routes",
});Example routegen.config.js:
const { routeConfig } = require("rrv7-routegen");
module.exports = routeConfig({
routeDir: "src/routes",
outDir: "generated",
outputFileName: "routes",
});Generated Output
The tool generates a file (e.g., .routegen/route-file) with a type-safe helper:
// AUTO-GENERATED — DO NOT EDIT
// Hash: 7ae3d5f2b9c0e4a1687d2e0f3b7a9c8d
export type RouteFilePath =
| "home"
| "comments/index"
| "comments/details"
| "settings";
export function routeFile(path: RouteFilePath) {
switch (path) {
case "home": return "./routes/homex";
case "comments/index": return "./routes/comments/indexx";
case "comments/details": return "./routes/comments/detailsx";
case "settings": return "./routes/settingsx";
default: throw new Error(`Invalid routeFile: ${path}`);
}
}Integration Example
Use the generated helper in your React Router v7 configuration:
// routes
import {
type RouteConfig,
index,
route,
prefix,
layout,
} from "@react-router/dev/routes";
import { routeFile } from "./routes-file";
export default [
index(routeFile("home")),
route("playground", routeFile("playground")),
...prefix("comments", [route("", routeFile("comments"))]),
] satisfies RouteConfig;Programmatic Usage
You can use the tool programmatically in your scripts:
import { runGeneration, runWatchMode } from "rrv7-routegen";
await runGeneration({ routeDir: "src/routes", outDir: "generated" });
await runWatchMode({ routeDir: "src/routes", outDir: "generated" });🧠 Route Detection Logic
The route detection system intelligently identifies valid React Router v7 route modules by analyzing:
- Export Patterns: Files with
action,loader, or default React component exports - Comment Analysis: The tool skips route files where the route-specific code is commented out:
- Line comments (
// export default function...) - Block comments (
/* export default function... */)
- Line comments (
- Component Heuristics: The tool identifies React components based on import patterns, JSX syntax, and naming conventions
Comment Handling Examples
Routes that will be detected:
import React from 'react';
// Regular comments are fine
export default function Home() {
return <div>Hello world</div>;
}
// This comment won't affect detection
export function loader() {
return { message: "Hello" };
}Routes that won't be detected (commented out):
import React from 'react';
// export default function Home() {
// return <div>Hello world</div>;
// }
// export function loader() {
// return { message: "Hello" };
// }
// Just a utility - not a route
export function formatDate(date) {
return new Date(date).toLocaleDateString();
}🧪 Testing
The project includes a comprehensive test suite using Bun's test runner. Tests cover:
- Route detection logic (
route-detection.test) - Comment detection in routes
- Route file generation (
generator.test) - Smart diffing to avoid unnecessary regeneration
- Watch mode functionality (
watch.test) - Configuration loading (
load-config.test)
Run tests with:
bun test❓ FAQ
Q: How does the tool detect route modules?
A: It analyzes files for React Router v7-specific exports (action, loader, or a default React component) using TypeScript's AST parser.
Q: How are commented-out routes handled?
A: The tool uses AST analysis to detect if route module code is inside comments (both line and block comments) and skips those files when generating routes.
Q: How does the tool avoid unnecessary rebuilds?
A: It stores a hash of the current route configuration and only regenerates the output file when the routes have actually changed.
Q: How are nested routes handled?
A: Nested directories are flattened to slash notation in the RouteFilePath type (e.g., comments/indexx → "comments/index").
Q: Can I use JavaScript files instead of TypeScript?
A: Yes, the tool supports .js, .jsx, ``, and x files.
Q: Can I customize the route key format?
A: Not currently, but future versions may add a routeKeyFormat config option.
**Q: Why does watch mode fail with Yarn
