💪 Fully written in TypeScript
🌲 Composition support with splitted trees
🚀 Works anywhere
🫕 Zero dependencies
🪶 Lightweight (gzip: 1.38 KiB)
Typescript 4.7+
Install package:
npm install @mc-petry/route-tree
Construct routes:
// Create builder
const builder = routeBuilder(options)
// Create tree
const tree = builder.tree({
user: segment({
children: {
id: param(),
},
}),
})
// Build routes
const routes = builder.build(tree)
Use it anywhere:
routes.user.$.route() // `/home`
routes.users.id.$.route({ id: 'John' }) // `/users/John`
routes.users.id.$.path // `:id`
routes.users.id.$.pattern // `/users/:id`
interface RouteBuilderConfig {
/**
* Global routes prefix.
* @default '/'
*/
basePath?: string
/**
* Use trailing slash on routes
* @default false
*/
trailingSlash?: boolean
}
/**
* Returns route that match specified pathname.
*/
routes.$.find(pathname: string, options?: { depth?: number }): Route | null
const routes = builder.build(
builder.tree({
home: segment({
meta: { hidden: true },
}),
})
)
// Example usage
routes.home.$.meta.hidden === true
const home = builder.tree(...)
const users = builder.tree(...)
const routes = builder.build({
...home,
...users
})
builder.tree({
color: segment({
id: param().setType<'grey' | 'yellow'>(),
}),
})