@modern-helpers/router
TypeScript icon, indicating that this package has built-in type declarations

0.5.0 • Public • Published

@modern-helpers/router

Minimalistic router for modern web apps.

📖 Documentation

↗️ Demos

Features

Usage example

HTML

<a href="/hello">Say Hello</a>
<a href="/bye/">Say Goodbye</a>
<a href="/unknown-path">Wrong link</a>
<div id="outlet">default view</div>

JS

import { AbstractRouter } from "https://cdn.skypack.dev/@modern-helpers/router";
// or, using npm i @modern-helpers/router
// import { AbstractRouter } from "@modern-helpers/router";

const routerOutlet = document.getElementById("outlet");
function render(template) {
  routerOutlet.innerHTML = template;
}

const ROUTES = {
  "/": "<p>Home view</p>",
  "/hello": `<p>Hello World!</p>`,
  /** "directory" route for relative links */
  "/bye/": `<p>Good bye!</p>
    <p><a href="./soon">tell me more with a relative link</a></p>`,
  /** "child" route */
  "/bye/soon": `<p>Just a child route to say "see you soon".</p>`,
  /** default route */
  "/404": `<p>404: route not found</p>`,
};

class AppRouter extends AbstractRouter {
  async renderOrRedirect(path, options) {
    if (!Object.keys(ROUTES).includes(path)) {
      // redirection to the default route
      return ["/404", options];
    }

    render(ROUTES[path]);
  }
}

async function runRouter() {
  const appRouter = new AppRouter();

  // listen clicks and popstate on body
  // and run a first navigation using window.location.pathname
  await appRouter.run();
}

runRouter();

Package Sidebar

Install

npm i @modern-helpers/router

Weekly Downloads

2

Version

0.5.0

License

MIT

Unpacked Size

39.3 kB

Total Files

23

Last publish

Collaborators

  • noelmace