npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-router-routepathgen

v0.1.0-alpha.1

Published

Generate route file paths based on route module names for React Router apps

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/routes for React Router v7 route modules (with action, loader, or default component exports).
  • 🛡️ Type-Safe Helpers: Generates a routeFile() function with a RouteFilePath type 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/js file, 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/indexxcomments/index).
  • 🧩 JavaScript & TypeScript: Compatible with .js, .jsx, ``, and x files.
  • 🚀 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 --dev

As a Vite Plugin

# Using npm
npm install rrv7-routegen --save-dev

# Using Bun
bun add rrv7-routegen --dev

Note: The Vite plugin requires vite (^5.0.0 or ^6.0.0) as a peer dependency.

For Local Development (Linking)

  1. From the rrv7-routegen project root:

    # Build the package
    bun run build
       
    # Link globally
    bun link
  2. In 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.

  1. 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',
        }),
      ],
    });
  2. Optionally, use a routegen.config or routegen.config.js file for configuration (merged with Vite config options):

    // routegen.config
    import { routeConfig } from 'rrv7-routegen';
    
    export default routeConfig({
      routeDir: 'src/routes',
      outDir: 'generated',
      outputFileName: 'routes',
    });
  3. Run Vite:

    vite

    The 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
    └── settingsx

CLI Commands

Generate the route file once:

bunx rrv7-routegen generate
# or
npx rrv7-routegen generate

Watch for changes and regenerate automatically:

bunx rrv7-routegen watch
# or
npx rrv7-routegen watch

Default behavior (runs generate if no command is specified):

bunx rrv7-routegen
# or
npx rrv7-routegen

CLI 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 routes

Configuration 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:

  1. Export Patterns: Files with action, loader, or default React component exports
  2. 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... */)
  3. 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