svelte-html-router

Lightweight Svelte 5 router with history and hash mode, dynamic parameters, and navigation guards.

Features

  • Dual mode: history (default) and hash
  • Dynamic route parameters (/user/:id)
  • Automatic query parameter parsing
  • Navigation guards (beforeEach)
  • Link interception (auto-hijacks <a> clicks)
  • Wildcard routes (*) and redirects
  • Base path prefix
  • Full TypeScript type definitions
  • Svelte 5 Runes compatible

Installation

npm Install

# npm
npm install svelte-html-router

# cnpm(国内镜像)
cnpm install svelte-html-router

# yarn
yarn add svelte-html-router

# pnpm
pnpm add svelte-html-router

Peer Dependencies

Make sure the following dependencies are installed:

npm install svelte

ES Module Import

import { createRouter, RouterView, RouterLink } from 'svelte-html-router'

CommonJS Require

const { createRouter, RouterView, RouterLink } = require('svelte-html-router')

CDN Usage

You can also use it directly via CDN (for quick prototyping or online demos):

<script src="https://unpkg.com/svelte-html-router@1.2.0/dist/svelte-html-router.iife.js"></script>

Quick Start

import { createRouter, RouterView } from 'svelte-html-router'
import Home from './views/Home.svelte'
import About from './views/About.svelte'

const router = createRouter([
  { path: '/', name: 'home', component: Home },
  { path: '/about', name: 'about', component: About },
])

// App.svelte 中使用
// <RouterView {router} />

createRouter

Create a router instance. Accepts an array of route records or a configuration object.

Example

createRouter(options: RouterOptions | RouteRecord[]): RouterInstance

RouterOptions

PropertyTypeDefaultDescription
routesRouteRecord[]Route records array (required)
mode'history' | 'hash''history'Routing mode
basestring''Path prefix (history mode only)

Example

// 简写:直接传数组(默认 history 模式)
const router = createRouter([
  { path: '/', component: Home },
])

// 完整配置
const router = createRouter({
  mode: 'hash',
  base: '/app',
  routes: [
    { path: '/', component: Home },
    { path: '/user/:id', component: User },
    { path: '*', component: NotFound },
  ],
})

RouteRecord

Route record definition.

PropertyTypeRequiredDescription
pathstringYesRoute path, supports :param dynamic params and * wildcard
namestringRoute name
componentSvelteComponentYesSvelte component for this route
metaRecord<string, any>Route metadata
redirectstringRedirect target path

RouteLocation

Current route location info, subscribe via router.current.

PropertyTypeDescription
pathstringCurrent path
namestringMatched route name
paramsRecord<string, string>Dynamic parameters
queryRecord<string, string>Query parameters
metaRecord<string, any>Route metadata
matchedRouteRecord | nullMatched route record

RouterView

Route outlet component that renders the currently matched route component.

Props

PropertyTypeRequiredDescription
routerRouterInstanceYesRouter instance

Example

<!-- App.svelte -->
<script>
  import { RouterView } from 'svelte-html-router'
  import { router } from './routes'
</script>

<RouterView {router} />

Router Instance Methods

MethodParametersDescription
push(path)path: stringNavigate to a new path (creates history entry)
replace(path)path: stringNavigate to a new path (replaces current history entry)
back()Go back one step
forward()Go forward one step
go(n)n: numberGo forward/back n steps
beforeEach(guard)guard: NavigationGuardRegister a global navigation guard
buildHref(path)path: stringBuild href string (based on route mode)
init()Initialize router (listen to popstate / hashchange)
destroy()Destroy router (remove event listeners)

Properties

PropertyTypeDescription
currentReadable<RouteLocation>Current route location (use $current to subscribe)
routesRouteRecord[]All route records
mode'history' | 'hash'Current routing mode

Route Mode

History Mode (default)

Uses the browser History API with clean URLs (no # prefix). Requires server-side configuration to fallback all paths to index.html.

# Nginx 配置
location / {
  try_files $uri $uri/ /index.html;
}

Hash Mode

Uses URL hash (#), no server configuration needed, suitable for static hosting.

const router = createRouter({
  mode: 'hash',
  routes: [...],
})