![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
A small efficient framework-agnostic client-side routing library, written in TypeScript.
A small efficient framework-agnostic client-side routing library, written in TypeScript.
It is currently under development and API might slightly change.
Those features may be the ones you are looking for.
Esroute is written with no external dependencies, so it does not require you to use a library.
A configuration can look as simple as this:
import { defaultRouter } from "esroute";
const router = defaultRouter({
"/": ({ go }) => go("/foo"),
foo: () => load("routes/foo.html"),
nested: load("routes/nested/index.html"),
"nested/*": ({ params: [param] }) =>
load("routes/nested/dynamic.html", param),
});
router.onResolve(({ value }) => render(value));
You can of course compose the configuration as you like, which allows you to easily modularize you route configuration:
const router = defaultRouter({
"/": ({ go }) => go("/mod1"),
mod1: mod1Routes,
composed: {
...mod2Routes,
...mod3Routes,
},
});
The router can be restricted to allow only certain resolution types.
const router = defaultRouter<string>({
"/": () => "some nice value",
async: loadString(),
weird: () => 42, // TS Error
});
Note: You should never directly assign a route spec to a variable/constant of type RouteSpec<T, X>
. Instead, you should use the routeBuilder<T>
to make sure that typechecking works properly:
const routes = routeBuilder<string>();
export const routesChunk = routeBuilder({
"/": () => "some nice template",
"?": ({ go }) => !loggedIn && go("/login"),
});
Here is a TypeScript playground snapshot that highlights the issue without the routeBuilder function. If you come up with a better solution, a PR is very welcome.
Aside from this, you can pass your route spec inline into other functions like defaultRouter<T>()
, new Router<T>()
, compileRoutes<T>()
, verifyRoutes<T>()
.
esroute comes with no dependencies and is quite small.
The route resolution is done by traversing the route spec tree and this algorithm is based on simple string comparisons (no regex matching).
You can decide to use the more concise, but non-optimizable version of creating a router like this:
import { defaultRouter } from "esroute";
const router = defaultRouter(myRouteSpec, myConfig);
Or you can use the more verbose, but more tweakable approach. This is equivalent to short form setup listed above:
import {
Router,
compileRoutes,
defaultRouteResolver,
verifyRoutes,
} from "esroute";
const router = new Router(verifyRoutes(compileRoutes(routeSpec)), {
resolver: defaultRouteResolver(),
...myConfig,
});
When using the constructor, you can tweak performance even more:
verifyRoutes()
only at development time and let it tree-shake when bundling you app for productiondefaultRouteResolver
.Route guards provide a way to check whether the current route should be routed to. If the given route resolution should not be applied, you can redirect to another route.
A guard can be applied to any route and it is called for the route it was applied to and it's sub-routes.
const router = new Router({
members: {
...protectedRoutes,
"?": ({ go }) => isLoggedIn || go(["login"]),
},
login: () => renderLogin(),
});
The Router
constructor takes two arguments: A RouteSpec
and a RouterConf
object.
RouteSpec
Example:
{
"/": resolveIndex,
"?": ({ go }) => isLoggedIn || go(["login"]),
x: resolveX,
nested: {
"/": resolveNestedIndex,
y: resolveY,
level2: {
z: resolveZ,
"?": ({ go }) => isAdmin || go([]),
},
"*": {
"foo": ({ params: [myParam] }) => resolveFoo(myParam),
}
}
}
If you configure the routes like listed above, no compilation step is required.
For convenience, there is a compileRoutes()
function that you can use to write
routes in a maybe more concise way. Of course this precompilation has a bit of performance and payload cost. So if you have a lot of routes, you might consider using the already optimized format above.
compileRoutes({
"/users/*": {
"/posts/*": ({ params: [userId, postId] }) => resolvePost(userId, postId),
"/posts": ({ params: [userId] }) => resolvePostList(userId),
},
});
You can also compile only part of the routes like this:
{
users: {
"*": {
...compileRoutes({
"/posts/*": ({ params: [userId, postId] }) => resolvePost(userId, postId),
"/posts": ({ params: [userId] }) => resolvePostList(userId),
}),
},
},
}
To ensure that your routes are setup correctly, it makes sense to verify your routes configuration. For maximum performance and treeshakability, the route verification is not baked-in to the router. You can set it up such that it is only included at development time.
RouterConf
RouterConf
provides some router specific configuration:
interface RouterConf<T> {
notFound?: Resolve<T>;
noClick?: boolean;
}
RouterConf.notFound
can be used to provide a custom handler
when a route cannot be resolved. By default the resolution is
redirected to the /
route.
RouterConf.noClick
can be used to disable the default click behavior for anchor elements.
Router.onResolve((res: Resolved<T>) => void): () => void
A router instance holds a callback registry.
Your callback will be called initially with the currently resolved route and then every time a new route is resolved, but not yet placed on the history stack.
onResolve()
returns a function that you can call to unsubscribe the passed-in callback again.
Resolved<T>
looks like this:
interface Resolved<T> {
value: T;
opts: NavOpts;
}
So when the route is resolved, not only get passed the resolved value (for example a template or a DOM element), but also the NavOpts
instance to gain access to path variables, search params or the state.
FAQs
A small efficient framework-agnostic client-side routing library, written in TypeScript.
The npm package esroute receives a total of 2 weekly downloads. As such, esroute popularity was classified as not popular.
We found that esroute demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.