Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

unrouting

> 编程语言
Open source

Making filesystem routing universal

192 stars0 likes2 views
WebsiteGitHub

About

Making filesystem routing universal

unrouting

[![npm version][npm-version-src]][npm-version-href] [![npm downloads][npm-downloads-src]][npm-downloads-href] [![bundle][bundle-src]][bundle-href] [![Codecov][codecov-src]][codecov-href] [![License][license-src]][license-href] [![JSDocs][jsdocs-src]][jsdocs-href]

Universal filesystem routing

unrouting parses file paths into a route tree and emits route definitions for any framework router. It handles nested routes, dynamic params, catchalls, optional segments, route groups, layer merging, and more – as a standalone, framework-agnostic library.

Status

In active development. The core pipeline (parse, tree, emit) is functional and used by Nuxt.

  • Generic route parsing covering major filesystem routing patterns
    • Nuxt / unplugin-vue-router
    • SvelteKit
    • Next.js
  • Route tree with nesting, layer merging, group transparency
  • Layer priority (multiple roots with configurable file precedence)
  • Incremental tree updates (addFile/removeFile for dev server HMR)
  • Pluggable route name generation
  • Route ordering by segment priority (static > dynamic > optional > catchall)
  • Named view support (@viewName convention)
  • Mode variant support (.client, .server, configurable)
  • Duplicate route name detection
  • Emit to framework routers
    • vue-router (nested routes, names, files, children, meta, components, modes)
    • rou3/Nitro
    • RegExp patterns
    • SolidStart
    • SvelteKit

Install

bash
# npm
npm install unrouting

# pnpm
pnpm install unrouting

Usage

The library has a three-phase pipeline: parse file paths into tokens, build a route tree, and emit to a target format. For most use cases you only need two function calls.

Quick start

…

Nuxt-like usage with layers

…

Emitting to different formats

All emitters accept a RouteTree:

…

Incremental updates (dev server)

The route tree is mutable. Instead of rebuilding everything when a file changes, use addFile and removeFile to update the tree in place – avoiding the cost of re-parsing all files and reconstructing the tree from scratch on every change.

javascript
import { addFile, buildTree, removeFile, toVueRouter4 } from 'unrouting'

const opts = { roots: ['pages/'], extensions: ['.vue'] }

// Build once at startup
const tree = buildTree(initialFiles, opts)
let routes = toVueRouter4(tree)

// On file add/remove (e.g., from a watcher callback)
addFile(tree, 'pages/new-page.vue', opts)
routes = toVueRouter4(tree)

removeFile(tree, 'pages/old-page.vue')
routes = toVueRouter4(tree)

// Rename = remove + add
removeFile(tree, 'pages/old-name.vue')
addFile(tree, 'pages/new-name.vue', opts)
routes = toVueRouter4(tree)

addFile supports the same InputFile format as buildTree for layer priority:

javascript
addFile(tree, { path: 'layer/pages/about.vue', priority: 1 }, opts)

Standalone parsing and segment conversion

If you don't need the full tree pipeline – e.g., you already have resolved routes and only need to convert individual path segments or strings to Vue Router syntax – you can use the parse + convert functions directly:

…

Supported patterns

Pattern Example Description
Static about.vue Static route segment
Index index.vue Index page (maps to /)
Dynamic [slug].vue Required parameter
Optional [[slug]].vue Optional parameter
Catchall [...slug].vue Catch-all (zero or more segments)
Repeatable [slug]+.vue One or more segments
Optional repeatable [[slug]]+.vue Zero or more segments
Group (admin)/dashboard.vue Route group (transparent to path, stored in meta)
Mixed prefix-[slug]-suffix.vue Static and dynamic in one segment
Nested parent.vue + parent/child.vue Parent layout with child routes
Named views [email protected] Vue Router named view slots
Modes page.client.vue Mode variants (configurable suffixes)

API

buildTree(input, options?)

Build a route tree from file paths. Accepts raw strings, InputFile[] (with priority), or pre-parsed ParsedPath[].

typescript
function buildTree(
  input: string[] | InputFile[] | ParsedPath[],
  options?: BuildTreeOptions
): RouteTree

interface InputFile {
  path: string
  /** Lower number = higher priority. Default: 0 */
  priority?: number
}

Options (extends ParsePathOptions):

Option Type Description
roots string[] Root paths to strip (e.g., ['pages/', 'layer/pages/'])
extensions string[] File extensions to strip (default: strip all)
modes string[] Mode suffixes to detect (e.g., ['client', 'server'])
warn (msg: string) => void Warning callback for invalid characters in dynamic params
duplicateStrategy 'first-wins' | 'last-wins' | 'error' How to handle duplicate paths (default: 'first-wins')

When files from different layers collide at the same tree position, the file with the lowest priority number wins regardless of insertion order.

addFile(tree, filePath, options?)

Add a single file to an existing route tree in place. Parses the file and inserts it, avoiding a full rebuild. Accepts a plain string or InputFile with priority.

typescript
function addFile(
  tree: RouteTree,
  filePath: string | InputFile,
  options?: BuildTreeOptions
): void

removeFile(tree, filePath)

Remove a file from an existing route tree by its original file path. Prunes empty structural nodes left behind. Returns true if the file was found and removed.

typescript
function removeFile(tree: RouteTree, filePath: string): boolean

toVueRouter4(tree, options?)

Emit Vue Router 4 route definitions from a tree. Handles nested routes, names, index promotion, structural collapse, groups, catchall optimisation, route ordering, named views, and mode variants.

…

Routes are sorted by segment priority within each level: static segments first, then dynamic, optional, and catchall last.

toRou3(tree)

Emit rou3/Nitro route patterns from a tree.

typescript
function toRou3(tree: RouteTree): Rou3Route[]

interface Rou3Route {
  path: string
  file: string
}

vueRouterToRou3(path, options?)

Convert a compiled Vue Router path string (e.g. a route definition's path) into one or more rou3 patterns. Useful when you already have resolved Vue Router routes (not files) and need to feed them to rou3/Nitro, for example when a module rewrites paths at runtime.

…

Params carrying a finite alternation regexp are expanded into concrete paths; other custom regexps are preserved as rou3 param constraints where rou3 enforces them (plain and optional params). They are dropped on repeatable params (rou3 ignores them there) and when the regexp contains / (rou3 splits patterns on slashes and cannot represent it).

typescript
import { vueRouterToRou3 } from 'unrouting'

vueRouterToRou3('/:locale(de|fr)/account/verify').patterns
// => ['/de/account/verify', '/fr/account/verify']

vueRouterToRou3('/users/:id(\\d+)').patterns
// => ['/users/:id(\\d+)']

vueRouterToRou3('/:pathMatch(.*)*').patterns
// => ['/:pathMatch*']

With collapse: true, each path becomes a glob built from * and ** wildcards. This exists because some targets (route-rule keys, hosting provider config exports) only understand static prefixes and wildcard globs, not :param matchers. A bare whole-segment param (:id) maps exactly to a single-segment * wildcard, so no issue is reported and later segments stay intact. A bare optional param (:id?) becomes a trailing * (optional in rou3) or, mid-path, expands into both variants (with and without the segment). Anything a wildcard cannot represent exactly (a regexp constraint, a partial segment like prefix-:id, a repeatable param) collapses into a ** catch-all from that segment onwards, with a collapsed issue. Enumerable params are still expanded first, so the glob stays as narrow as possible.

typescript
vueRouterToRou3('/products/:id/edit', { collapse: true }).patterns
// => ['/products/*/edit']

vueRouterToRou3('/users/:id(\\d+)/edit', { collapse: true }).patterns
// => ['/users/**']

vueRouterToRou3('/:locale(de|fr)/account/:id', { collapse: true }).patterns
// => ['/de/account/*', '/fr/account/*']

vueRouterToRou3('/static/path', { collapse: true }).patterns
// => ['/static/path']

Conversions are best-effort: a collapsed catch-all matches more than the original path, repeatable params lose their regexp constraint (rou3 does not enforce them) and huge alternations fall back to plain dynamic params. Every such step is recorded in issues so callers can surface them to their users:

typescript
const { patterns, issues } = vueRouterToRou3('/products/:id(\\d+)', { collapse: true })
// patterns => ['/products/**']
// issues => [{ type: 'collapsed', message: 'Collapsed "/products/:id(\\d+)" at segment ":id(\\d+)" into a `**` catch-all, ...' }]

toRegExp(tree)

Emit RegExp matchers from a tree.

typescript
function toRegExp(tree: RouteTree): RegExpRoute[]

interface RegExpRoute {
  pattern: RegExp
  keys: string[]
  file: string
}

rou3PatternToURLPattern(pattern, options?)

Convert a single rou3/Nitro route pattern into a URLPattern pathname pattern (e.g. for a Speculation Rules href_matches rule, or new URLPattern({ pathname })). rou3 describes its syntax as URLPattern-compatible, so most tokens (:name, :name(regex), :name?, :name+, (regex), {...}) pass through unchanged. Only * and ** genuinely differ and are translated: rou3 * (single segment) becomes ([^/]*), and rou3 **/**:name (catch-all) becomes *.

typescript
function rou3PatternToURLPattern(pattern: string, options?: { segment?: 'strict' | 'loose' }): {
  pattern: string
  issues: Rou3ToURLPatternIssue[]
}

rou3PatternToURLPattern('/blog/**').pattern // => '/blog/*'
rou3PatternToURLPattern('/users/:id').pattern // => '/users/:id'
rou3PatternToURLPattern('/users/:id(\\d+)').pattern // => '/users/:id(\\d+)'

Pass { segment: 'loose' } to collapse single-segment tokens (:name, *) to * instead, matching Nuxt's historical inline conversion. This over-matches (a single * matches across /), so each collapse is recorded in issues:

typescript
const { pattern, issues } = rou3PatternToURLPattern('/users/:id', { segment: 'loose' })
// pattern => '/users/*'
// issues => [{ type: 'widened', param: 'id', message: 'Widened ":id" ...' }]

toVueRouterSegment(tokens, options?)

Convert a single parsed segment (an array of tokens returned by parseSegment) into a Vue Router 4 path segment string. Useful for modules that already have resolved routes and only need segment-level path conversion (e.g., @nuxtjs/i18n converting per-locale custom paths).

typescript
function toVueRouterSegment(
  tokens: ParsedPathSegmentToken[],
  options?: ToVueRouterSegmentOptions
): string

interface ToVueRouterSegmentOptions {
  /**
   * Whether non-index segments follow this one.
   * When true, catchall uses ([^/]*)*; when false (default), uses (.*)*
   */
  hasSucceeding?: boolean
}
javascript
import { parseSegment, toVueRouterSegment } from 'unrouting'

toVueRouterSegment(parseSegment('[id]')) // => ':id()'
toVueRouterSegment(parseSegment('[[opt]]')) // => ':opt?'
toVueRouterSegment(parseSegment('[...slug]')) // => ':slug(.*)*'
toVueRouterSegment(parseSegment('prefix-[slug]')) // => 'prefix-:slug()'

// i18n use case

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言