st-route
v1.0.2
Published
Tiny DOM routing library
Downloads
14
Maintainers
Readme
Nano library for client-side DOM routing
This is an exremely tiny, yet powerful library for HTML5 history API based DOM routing. st-route
makes client-side page navigation dead simple.
- ✅ Abstracts the HTML5 history API
- ✅ Tiny:
374 bytes
(best, brotli) -535 bytes
(worst, umd, gz) - ✅ Zero dependencies
- ✅ First class TypeScript support
- ✅ 100% Unit Test coverage
- ✅ TestCafé smoke tests
This is how using st-route
looks like:
import { tsx, render, Ref } from 'springtype';
import { $ } from 'st-query';
import { route, RouteRequest } from 'st-route';
const nav = route();
const HomePage = () => (
<div>
HomePage
<br />
<a href="/blog">Go to BlogPage</a>
</div>
);
const BlogPage = () => <div>BlogPage</div>;
const BlogArticlePage = ({ request }: { request: RouteRequest }) => (
<div>
Blog / show article:
{request.params.slug}
</div>
);
const RouteList = () => {
const containerRef: Ref = {};
nav.get('/', () => {
containerRef.current = $(containerRef.current).replaceWith(<HomePage />);
});
nav.get('/blog', () => {
containerRef.current = $(containerRef.current).replaceWith(<BlogPage />);
});
nav.get('/blog/article/:slug', (request: RouteRequest) => {
containerRef.current = $(containerRef.current).replaceWith(<BlogArticlePage request={request} />);
});
return <div ref={containerRef}>Loading...</div>;
};
render(<RouteList />);
// initial match after initial render
nav.match();
The following contract is made between the webapp and st-router
:
export interface API {
get(path: string, handler: RouteHandler): API;
match(path?: string): RouteRequest | false;
getRouteRegistrations(): Array<RouteRegistration>;
tokenizePath(path: string): TokenizedPath;
}
// calling route() returns the API object like:
// const nav = route();
// nav.get('/foo')
export route = () => API;
⚠️ Please make sure that you have a http server in place that can handle pushState
well (re-routes all HTTP GET
requests back to the index.html
file serving the JavaScript). Please read about "SPA / Single Page Application routing" if you have any further questions about this.
Thank you so much for supporting us financially! 🙏🏻😎🥳👍
st-route
is brought to you by:
Original implementation of the routing logic is based on ideas of LeviRoutes developed by Paul Kinlan about 10 years ago -- however, this is a TypeScript-based clean room re-implementation which improves the original code in a few aspects.
Please help out to make this project even better and see your name added to the list of our CONTRIBUTORS.md :tada: