route-descriptor
This package provides an interface to statically represent routing configuration in your application. It lets you establish a single source of truth for generating links, which avoids code duplication and makes refactoring easier. Works best with TypeScript.
Download
- npm:
npm i route-descriptor
Features
- Supports static and dynamic routes
- Supports positional and query parameters
- Parameter validation via TypeScript
- Works in browser and NodeJS
Usage
Routes with parameters
The following example creates a dynamic route called product
with expected parameters declared in ProductParams
. The route itself is a function that can be invoked to resolve the actual URL:
; ; ; // '/products/3'
Routes with query parameters
Any parameters that don't match with keys in the route path are automatically mapped as query parameters:
; ; ; // '/products/3?showComments=true'
Routes without parameters
You can also create a static route, i.e. such that doesn't expect any parameters. Invoking it simply returns the path without any replacements:
; ; ; // '/home'
Routes with optional positional parameters
Some routes may have positional parameters which are optional. They need to be marked with the ?
modifier in the path template:
; ; ; // '/profile/13'
Retrieving the path
Once the route is created, you can get the original path back too. This may be convenient when plugging route-descriptor
into a routing library of your choice:
; ; ; // '/profile/:id/:name?'
react-router
Combining with It's possible to use route-descriptor
with pretty much any client-side routing library. For example, here is how to integrate it with react-router
:
./src/routes.ts
:
; ;
./src/App.tsx
:
;;
As you can see, the routes are defined in a single place (the routes.ts
module) from which they referenced throughout the application. This makes changing the paths and route parameters easy in the future, as you don't have to worry about updating URLs in every anchor tag.
TypeScript integration
This package is most useful when paired with TypeScript, as it provides static validation for parameters. For example, all of the following incorrect usages produce errors during compilation:
; ;home; // <- error (static route can't accept parameters) ;product; // <- error (dynamic route requires parameters)product; // <- error (missing 'id')product; // <- error (unexpected 'name')
If you want, it's also possible to use route-descriptor
with plain JavaScript, which is still useful for establishing a single source of truth, but doesn't help with parameter validation:
; // Works in plain JSconst product = ;const href = ;