2.6 KiB
2.6 KiB
Svelte 5 Micro-Router (File-Based)
This is a lightweight, custom-built file-based router for Svelte 5 that mimics the SvelteKit routing system for standalone Single Page Applications (SPA) powered by Vite.
🚀 Features
- File-based Routing: Automatically detects and maps
.sveltefiles inside theroutesdirectory. - Dynamic Routes: Full support for dynamic parameters using the
[id].sveltesyntax. - Svelte 5 Native: Built using Runes (
$state,$props,{@render}) for reactive performance and modern syntax. - Zero Dependencies: No heavy routing libraries required; uses native Browser APIs.
📁 Recommended Directory Structure
The router scans for files within src/routes/. Your project should look like this:
src/
├── routes/
│ ├── index.svelte // Route: /
│ ├── about-us.svelte // Route: /about-us
│ └── post/
│ └── [id].svelte // Route: /post/:id
└── App.svelte // Import and use this Router here
🛠️ How it Works
1. Route Scanning
The router uses import.meta.glob to analyze your file system at build time. It converts file paths into Regular Expressions:
index.svelte➔/[id].svelte➔/(?<id>[^/]+)(Captures the ID as a Regex group).
2. Navigation Interception
The component attaches a global Click Event Listener to the window. When a user clicks an internal <a> tag:
- It prevents the default page reload (
e.preventDefault()). - It updates the URL via the History API (
pushState). - It triggers the
update()function to swap the UI component.
4. Dynamic Rendering
By using the {#key CurrentPage} block, the router ensures that components are properly destroyed and re-mounted when navigating between different instances of the same route (e.g., navigating from /post/1 to /post/2).
💻 Usage in App.svelte
<script>
import Router from './lib/Router.svelte';
</script>
<Router>
{#snippet loading()}
<div class="spinner">Loading page...</div>
{/snippet}
{#snippet fallback()}
<div class="error">
<h1>404</h1>
<p>The page you are looking for does not exist.</p>
<a href="/">Go back home</a>
</div>
{/snippet}
</Router>
⚠️ Current Limitations
- Nesting: Does not support nested
layout.sveltefiles automatically (requires extra logic). - Preloading: Components are loaded only when the navigation occurs.
- Query Params: While they won't break the app, they are currently ignored by the parameter parser.