--- # 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 `.svelte` files inside the `routes` directory. * **Dynamic Routes:** Full support for dynamic parameters using the `[id].svelte` syntax. * **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: ```text 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` ➔ `/(?[^/]+)` (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 `` tag: 1. It prevents the default page reload (`e.preventDefault()`). 2. It updates the URL via the **History API** (`pushState`). 3. 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 ```svelte {#snippet loading()}
Loading page...
{/snippet} {#snippet fallback()}

404

The page you are looking for does not exist.

Go back home
{/snippet} ``` ## ⚠️ Current Limitations * **Nesting:** Does not support nested `layout.svelte` files 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. ---