---
name: svelte
description: Modern Svelte development for reactive web apps. Use when building Svelte components, managing state with stores, implementing real-time updates via WebSocket, or migrating from vanilla JS. Covers SvelteKit, TypeScript, and integration with Node.js backends.
---
# Svelte Skill
## Overview
This skill provides expertise for building reactive web applications with Svelte. It covers component architecture, the reactivity system, stores for state management, real-time updates with WebSockets, and SvelteKit for full-stack applications.
## Why Svelte
### Comparison with Vanilla JS
| Aspect | Vanilla JS | Svelte |
|--------|------------|--------|
| Reactivity | Manual DOM updates | Automatic - `count++` just works |
| Components | Template strings | Single-file components |
| State | Global variables | Stores with subscriptions |
| Bundle size | 0kb (but more code) | ~2kb runtime |
| Learning curve | None | Gentle (closest to vanilla) |
### Key Benefits
1. **Compile-time magic** - No virtual DOM, compiles to efficient vanilla JS
2. **Less boilerplate** - `let count = 0` is reactive by default
3. **Built-in transitions** - `transition:fade` for animations
4. **Scoped CSS** - Styles in components don't leak
5. **Stores** - Simple reactive state that works with WebSockets
## Core Concepts
### Reactivity
Svelte's reactivity is based on assignments:
```svelte
```
### Array/Object Reactivity
Svelte tracks assignments, not mutations:
```svelte
```
### Component Structure
Single-file components with script, markup, and style:
```svelte
{name}
Cash: £{cash}
{#if expanded}
{/if}
```
### Using Components
```svelte
{#each players as player (player.id)}
Ships: {player.ships?.length ?? 0}
{/each}
```
## Stores
### Writable Stores
For shared state across components:
```javascript
// stores/gameState.js
import { writable, derived } from 'svelte/store';
// Create a writable store
export const gameState = writable(null);
// Derived stores compute from other stores
export const currentPlayer = derived(
gameState,
$state => $state?.players?.[$state?.currentPlayerIndex]
);
export const isMyTurn = derived(
[gameState, currentPlayer],
([$state, $player]) => $player?.id === myPlayerId
);
// Helper functions to update state
export function updateGameState(newState) {
gameState.set(newState);
}
export function updatePlayer(playerId, changes) {
gameState.update(state => ({
...state,
players: {
...state.players,
[playerId]: { ...state.players[playerId], ...changes }
}
}));
}
```
### Using Stores in Components
```svelte