npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@captaincodeman/router

v1.0.3

Published

ultra-lightweight client-side router

Downloads

895

Readme

@captaincodeman/router

typescript types included normal size gzipped size brotli size

An ultra-tiny client-side router for modern Progressive Web Apps (PWAs) or Single Page Apps (SPAs).

This tiny module exports a single function, that takes an object of URL patterns and returns a matcher function. The matcher function then can be called to get the match, based on the URL.

It's all I need for routing and helps when trying to reduce the size of client apps.

routes.js

import createMatcher from '@captaincodeman/router'
import homeView from './views/home'
import todoListView from './views/todo-list'
import todoDetailView from './views/todo-detail'
import articleView from './views/article'

export default createMatcher({
  '/': homeView,
  '/todos': todoListView,
  '/todos/:id': todoDetailView,
  '/article/*': articleView
})

This returns a function, that can be called to retrieve the value, along with extracted parameters:

other.js

import routeMatcher from './routes'

// call it with a pathname you want to match
routeMatcher('/')
// =>
// {
//   page: homeView,
//   params: { }
// }

routeMatcher('/todos')
// =>
// {
//   page: todoListView,
//   params: { }
// }

routeMatcher('/todos/41237')
// =>
// {
//   page: todoDetailView,
//   params: {
//     id: '41237'
//   }
// }

routeMatcher('/articles/some/other/path')
// =>
// {
//   page: articleView,
//   params: {
//     path: 'some/other/path'
//   }
// }

routeMatcher('/not-a-page')
// =>
// null

Note that a failed match returns null, allowing you to provide whatever fallback you want (such as a 'page not found' view).

Also note, that page will be whatever you provided when you created the route matcher function (i.e. in the example above that is the call to createMatcher( ... )). It may be a simple string, a class, an object... It's really up to the rest of your application. Use what serves your app best; the router won't do anything with it (except returning it on a match).

Why is this useful?

In a Single Page App you'll need to determine what should be displayed based on the current URL. Part of the URL will determine the view to show and part will be parameters that determine which data should appear in that view. This package makes it easy to parse and extract both of those.

If you are using redux for application state, then there is a good argument for making the routing system part of that. Decisions such as which data to fetch can then be part of the application state, instead of residing in UI components. That can improve performance, as data can be pre-fetched to reduce latency, instead of waiting for an empty view to load and render, before requesting the data.

How parameter extraction works

Let's have a look at how route patterns and params work together.

Parameters

Use a :name format for parameters:

  • pattern: '/todos/:id'
  • URL: '/todos/123'
  • extracted params: { id: '123' }

Multiple parameters and static segments can be mixed:

  • pattern: '/topic/:topic/post/:post'
  • URL: '/topic/123/post/456'
  • extracted params: { topic: '123', post: '456' }

Parameters can be made optional:

  • pattern: '/topic/:topic(/post/:post)'
  • URL: '/topic/123'
  • extracted params: { topic: '123' }

Wildcards capture the remainder of the match into a param called path:

  • pattern: /blog/*
  • URL: '/blog/2019-11-12/how-to-use-client-routing'
  • extracted params: { path: '2019-11-12/how-to-use-client-routing' }

Notes

Things to be aware of...

  1. Order is important, the first match wins.
  2. If you re-use parameter names in the URL pattern, they'll be overwritten in the result.
  3. If you need query string values, match the base URL first with this module, then use the browser's built-in URLSearchParams to parse them.
  4. Be sure to configure your web server correctly: All requests (that are not static assets / files, like images or style sheets) must be handed to your application, otherwise you may face HTTP 404 (not found) errors generated by the web server, before your app can even ask the router for a match.

Install

npm install @captaincodeman/router --save

Credits

This was based on feather-route-matcher by HenrikJoreteg which itself borrows a few extremely well-tested regexes from Backbone.js to do its pattern matching. I converted it to TypeScript, fixed a couple of quirks with pattern matching and shaved off a few bytes from the size. Thanks for the generous licensing!

Building

Build the library using

npm run build

Tests

Run unit tests using

npm run test