---
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
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}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'); }); ```