@ryanmorr/router
v3.0.4
Published
A minimalist universal router for web applications
Downloads
23
Readme
router
A minimalist universal router for web applications
Install
Download the CJS, ESM, UMD versions or install via NPM:
npm install @ryanmorr/router
Usage
Create a router that matches different routes and extracts the parameters to pass to the callback function:
import Router from '@ryanmorr/router';
const router = Router({
'/': () => {
// Handle home page
},
'/foo': () => {
// Handle "/foo"
},
'/foo/:bar': ({bar}) => {
// Parameters are indicated by a prefixed colon
},
'/foo/:bar/:baz?': ({bar, baz}) => {
// Optional parameters are indicated by a suffixed question mark
},
'/foo/qux/*': ({wildcard}) => {
// An asterisk indicates a wildcard that will match anything
}
});
// Finds the first matching route and invokes the callback function
router.dispatch('/foo');
Use in a browser:
window.addEventListener('popstate', () => {
router.dispatch(window.location.pathname);
});
Use in Node.js:
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const path = url.parse(req.url).pathname;
router.dispatch(path);
});
server.listen(8888);
License
This project is dedicated to the public domain as described by the Unlicense.