--- description: Definitive guide for writing clean, performant, and maintainable Svelte 5 applications using the runes API and modern TypeScript practices. globs: **/*.{svelte,js,ts} --- # Svelte Best Practices (Svelte 5 + TypeScript) This guide outlines the definitive best practices for developing Svelte 5 applications with TypeScript. We prioritize explicit reactivity, strong typing, and compiler-driven performance. ## 1. Code Organization and Structure Always structure your Svelte components for clarity and maintainability. ### 1.1. HTML-First Component Design Keep your component logic, markup, and styles co-located within the `.svelte` file. This is Svelte's core philosophy. **❌ BAD: Over-abstracting into separate JS files for simple logic** ```svelte ``` **✅ GOOD: Keep related logic within the component** ```svelte ``` ### 1.2. TypeScript Everywhere Use `lang="ts"` in all ` ``` **✅ GOOD: Explicitly enable TypeScript** ```svelte ``` ## 2. Component Architecture (Svelte 5 Runes) Svelte 5's runes API makes reactivity explicit and powerful. Embrace it fully. ### 2.1. Explicit Reactive State with `$state` Declare all reactive state using `$state`. This makes your component's reactivity clear and refactor-friendly. **❌ BAD: Implicit reactivity (Svelte 4 style)** ```svelte ``` **✅ GOOD: Explicit `$state` for all reactive variables** ```svelte ``` ### 2.2. Derived State with `$derived` Use `$derived` for any value that is a pure computation of other reactive state. **❌ BAD: `$effect` or `$:` for derived values** ```svelte ``` **✅ GOOD: `$derived` for pure computations** ```svelte ``` ### 2.3. Side Effects with `$effect` Reserve `$effect` for actual side effects (e.g., DOM manipulation, API calls, logging). **❌ BAD: Mixing derivations and effects** ```svelte ``` **✅ GOOD: Clear separation of concerns** ```svelte ``` ### 2.4. Component Properties with `$props` Declare all component properties using the `$props()` rune and destructuring. This provides powerful type safety and flexibility. **❌ BAD: `export let` (Svelte 4 style)** ```svelte ``` **✅ GOOD: `$props()` for properties** ```svelte ``` ### 2.5. Event Handling Remove the `on:` prefix for event handlers. They are now standard properties. **❌ BAD: `on:click`** ```svelte ``` **✅ GOOD: `onclick` (standard HTML attribute)** ```svelte ``` ### 2.6. Slots and Snippets Use `{@render}` for rendering slots and snippets, providing type safety and better control over content. **❌ BAD: Untyped slots** ```svelte ``` **✅ GOOD: Typed snippets for predictable content** ```svelte
{@render header()}
``` ## 3. State Management Prioritize local component state with `$state`. Use Svelte stores for truly global or complex cross-component state. ### 3.1. Local State First Most state should live within the component using `$state`. **❌ BAD: Over-reliance on global stores for simple component state** ```svelte // store.ts import { writable } from 'svelte/store'; export const localCounter = writable(0); // Unnecessary global ``` **✅ GOOD: Use `$state` for component-local reactivity** ```svelte ``` ### 3.2. Svelte Stores for Global State For state shared across many components or complex application-wide state, use Svelte's built-in stores. ```ts // src/lib/stores/auth.ts import { writable } from 'svelte/store'; export const isAuthenticated = writable(false); export const user = writable<{ id: string; name: string } | null>(null); ``` ```svelte {#if $isAuthenticated}

Welcome, {$user?.name}!

{:else}

Please log in.

{/if} ``` ## 4. Performance Considerations SvelteKit handles many optimizations automatically. Supplement these with mindful coding. ### 4.1. `{#each}` with Keys Always provide a unique `key` to `{#each}` blocks for efficient DOM updates. **❌ BAD: Missing `key`** ```svelte {#each items as item} {/each} ``` **✅ GOOD: Use a unique `key`** ```svelte {#each items as item (item.id)} {/each} ``` ### 4.2. Dynamic Imports for Lazy Loading Lazy-load components or modules that aren't immediately needed to reduce initial bundle size. ```svelte {#if showModal} {/if} ``` ## 5. Common Pitfalls and Gotchas Avoid these common mistakes to ensure robust and predictable Svelte applications. ### 5.1. Misunderstanding `$effect` Dependencies `$effect` runs when its *dependencies* change. Be explicit about what it depends on. **❌ BAD: Implicit dependencies or missing cleanup** ```svelte ``` **✅ GOOD: Explicit dependencies and cleanup** ```svelte ``` ### 5.2. Forgetting `generics` Attribute When creating generic components, remember to add the `generics` attribute to the ` ``` **✅ GOOD: Explicit generics for type safety** ```svelte ``` ## 6. Accessibility Build accessible Svelte applications by default. ### 6.1. Semantic HTML Always prefer semantic HTML elements over generic `div`s or `span`s. **❌ BAD: Non-semantic button** ```svelte
Click me
``` **✅ GOOD: Semantic HTML element** ```svelte ``` ### 6.2. ARIA Attributes Use ARIA attributes when semantic HTML isn't sufficient, but only when necessary. ```svelte

Your username must be unique.

``` ## 7. Testing Approaches Implement a robust testing strategy for Svelte applications. ### 7.1. Unit Testing with Vitest and Svelte Testing Library Use `vitest` for your test runner and `@testing-library/svelte` for component testing. ```ts // src/lib/components/Counter.test.ts import { render, screen } from '@testing-library/svelte'; import { expect, test } from 'vitest'; import Counter from './Counter.svelte'; test('Counter increments value on click', async () => { render(Counter); const button = screen.getByRole('button', { name: /Count:/i }); expect(button).toHaveTextContent('Count: 0'); await button.click(); expect(button).toHaveTextContent('Count: 1'); }); ``` ### 7.2. End-to-End (E2E) Testing For critical user flows, use `Playwright` or `Cypress`. ```ts // tests/example.spec.ts (Playwright) import { test, expect } from '@playwright/test'; test('homepage has title and intro text', async ({ page }) => { await page.goto('/'); await expect(page).toHaveTitle(/SvelteKit/); await expect(page.locator('h1')).toHaveText('Welcome to SvelteKit'); }); ```