Universal Router is a simple middleware-style router that can be used in both client-side and server-side applications.
Features
- It has simple code
with only single path-to-regexp dependency. - It can be used with any JavaScript framework such as
React, Vue, Hyperapp etc. - It uses the same middleware approach used in Express and Koa,
making it easy to learn. - It supports both imperative and
declarative routing style. - Routes are plain JavaScript
objects
with which you can interact as you like.
Installation
Using npm:
npm install universal-router --save
Or using a CDN like
unpkg.com or
jsDelivr
with the following script tag:
<script src="https://unpkg.com/universal-router/universal-router.min.js"></script>
You can find the library in window.UniversalRouter
.
How does it look like?
import UniversalRouter from 'universal-router'
const routes = [
{
path: '', // optional
action: () => <h1>Home</h1>
},
{
path: '/posts',
action: () => console.log('checking child routes for /posts'),
children: [
{
path: '', // optional, matches both "/posts" and "/posts/"
action: () => <h1>Posts</h1>
},
{
path: '/:id',
action: (context) => <h1>Post #${context.params.id}</h1>
}
]
}
]
const router = new UniversalRouter(routes)
router.resolve('/posts').then(html => {
document.body.innerHTML = html // renders: <h1>Posts</h1>
})
Play with an example on JSFiddle,
CodePen,
JS Bin in your browser or try
RunKit node.js playground.
Documentation
Browser Support
We support all ES5-compliant browsers, including Internet Explorer 9 and above,
but depending on your target browsers you may need to include
polyfills for
Map
,
Promise
and
Object.assign
before any other code.
For compatibility with older browsers you may also need to include polyfills for
Array.isArray
and Object.create
.
Reference
Below are the reference links:
No. | Link |
---|---|
1. | Read more here. |
2. | Follow code author here. |