Vanilla JS/TS router
- Concise API for SPA navigation
- Flexible URL pattern matching for URL-based rendering
- Navigation middleware
Installation: npm i @t8/router
import { Route } from "@t8/router";
let route = new Route();🔹 The new Route(location) constructor accepts an optional URL location. In the browser, the current URL is implied if location is omitted.
- window.location.assign("/intro");
+ route.assign("/intro");
- window.location.replace("/intro");
+ route.replace("/intro");
- window.location.href = "/intro";
+ route.href = "/intro";
- console.log(window.location.href);
+ console.log(route.href);🔹 The route navigation API is largely in line with the built-in navigation APIs. An instance of Route exposes: .assign(url), .replace(url), .reload(), .href, .pathname, .search, .hash, .back(), .forward(), .go(delta) — similar to the built-in APIs of window.location and history carried over to route-based SPA navigation.
route.on("navigationstart", href => {
if (hasUnsavedChanges)
return false; // prevents navigation
if (href === "/") {
route.assign("/intro"); // redirection
return false; // prevents navigation
}
});route.on("navigationcomplete", href => {
if (href === "/intro")
document.title = "Intro";
});🔹 Both event handlers, acting like routing middleware, are immediately called when they are added if the route is already in the navigation-complete state.
console.log(route.href === "/intro");
console.log(route.href.startsWith("/sections/"));
console.log(/^\/sections\/\d+\/?/.test(route.href));let { ok, params } = route.match(/^\/sections\/(?<id>\d+)\/?/);
console.log(ok, params.id);header.className = route.at("/", "full", "compact");
// at "/" ? "full" : "compact"
let sectionTitle = route.at(
/^\/sections\/(?<id>\d+)\/?/,
({ params }) => `Section ${params.id}`
);
// at "/sections/<id>" ? "Section <id>" : undefined🔹 Type-safe params can be obtained by providing a type-safe URL pattern, such as produced by url-shape, to route.match(pattern) or route.at(pattern, x, y).
route.observe(document);The above line turns all <a> and <area> elements in the document to SPA route links enabling navigation without page reloads via the route object.
🔹 route.observe(container, elements) accepts a container element (it can be document, as in the example above) and optionally elements (which can be a selector or HTML elements).