Svelte Router screenshot

Svelte Router

Author Avatar Theme by Bluwy
Updated: 21 Jul 2023
34 Stars

An easy-to-use SPA router for Svelte

Overview

The Svelte Router is a package that provides an easy-to-use Single Page Application (SPA) router for Svelte, a JavaScript framework for building user interfaces. It supports both hash and path-based navigation, nested routes, redirects, navigation guards, lazy loading routes, and automatic base tag navigation. However, it does not support server-side rendering (SSR) or relative navigations.

Features

  • Super simple API: The Svelte Router has a straightforward API that is easy to understand and use.
  • Support for hash and path-based navigation: It allows navigation using both hash and path-based URLs.
  • Nested routes: The router supports the creation of nested routes, allowing for a hierarchical structure.
  • Redirects and navigation guards: The Svelte Router supports redirects and navigation guards, which can be used to control the navigation flow.
  • Lazy loading routes: It supports lazy loading of routes, allowing for better performance by loading only the necessary code when needed.
  • Auto base tag navigation: The router automatically handles base tag navigation, making it easier to ensure correct routing behavior.

Installation

To use the Svelte Router, you first need to install the package using npm:

npm install @bjornlu/svelte-router

Once installed, you can define your routes using the router’s API. Here’s an example:

import { Router, Link } from '@bjornlu/svelte-router';

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
  { path: '/contact', component: Contact },
];

const router = new Router({ routes });

After defining your routes, you can render them in your Svelte component and use the Link component to navigate between routes:

<nav>
  <Link to="/">Home</Link>
  <Link to="/about">About</Link>
  <Link to="/contact">Contact</Link>
</nav>

<router.view />

And that’s it! You have successfully installed and used the Svelte Router in your Svelte project.

Summary

The Svelte Router is a package that provides an easy-to-use SPA router for Svelte. It offers a simple API, support for hash and path-based navigation, nested routes, redirects and navigation guards, lazy loading routes, and auto base tag navigation. However, it does not support server-side rendering or relative navigations. Overall, it is a useful tool for managing the navigation flow in Svelte applications.