@captaincodeman/router
v1.0.3
Published
ultra-lightweight client-side router
Downloads
895
Maintainers
Readme
@captaincodeman/router
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...
- Order is important, the first match wins.
- If you re-use parameter names in the URL pattern, they'll be overwritten in the result.
- 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. - 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