Public Wiki85,706View on GitHub
Want sveltejs/svelte knowledge in your AI?

TypeScript

This is the Svelte framework source code - a compiler-based JavaScript UI framework that transforms .svelte component files into highly optimized vanilla JavaScript at build time. It includes the Svelte compiler (parsing, analysis, code generation), client-side runtime with fine-grained reactivity using signals, server-side rendering runtime, and a migration tool for upgrading Svelte 4 to Svelte 5 syntax.

Tech Stack

TypeScriptVitest

Key Features

  • Multi-phase Compiler
  • Signal-based Reactivity
  • DOM Block Constructs
  • Two-way Bindings
  • SSR Runtime
  • Svelte 4 to 5 Migration Tool
  • Reactive Built-in Wrappers

Entry Points

Start here when working with this codebase

Compiler Entry
packages/svelte/src/compiler/index.js

Main compiler entry point that orchestrates parsing, analysis, and transformation phases

Start here when modifying how Svelte components are compiled, adding new syntax, or changing code generation

Client Runtime Entry
packages/svelte/src/internal/client/index.js

Exports all client-side runtime functions used by compiled components

Start here when adding new runtime features, modifying reactivity behavior, or changing DOM operations

Server Runtime Entry
packages/svelte/src/internal/server/index.js

Server-side rendering runtime and context management

Start here when modifying SSR behavior, adding server-only features, or fixing hydration issues

Public Reactivity API
packages/svelte/src/reactivity/index.js

Public reactive wrappers exposed to users (SvelteDate, SvelteMap, SvelteSet, SvelteURL)

Start here when adding new reactive built-in wrappers or modifying existing reactive primitives

Store Module
packages/svelte/src/store/index.js

Svelte store implementation (writable, readable, derived)

Start here when modifying store behavior or adding new store types

Migration Tool
packages/svelte/src/compiler/migrate/index.js

Automated migration from Svelte 4 to Svelte 5 syntax

Start here when adding new migration rules or fixing migration edge cases

How to Make Changes

Common modification patterns for this codebase

Add a new compiler warning or error

1
packages/svelte/messages/compile-warnings/template.md

Add warning message definition in markdown format with code and description

Pattern: Follow format in packages/svelte/messages/compile-warnings/a11y.md - use ## for code, then description

2
packages/svelte/src/compiler/phases/2-analyze/visitors/

Add validation logic in the appropriate visitor file (e.g., Element.js for element warnings)

Pattern: See packages/svelte/src/compiler/phases/2-analyze/visitors/RegularElement.js for how to call context.state.analysis.warnings.push()

3
packages/svelte/tests/validator/

Add test case with .svelte input and expected warnings in _config.js

Pattern: See packages/svelte/tests/validator/samples/ for test structure with input.svelte and _config.js

Conventions to follow:

Warning codes use snake_case (e.g., a11y_missing_attribute)Messages are defined in markdown files, not inline in codeRun 'pnpm generate:messages' after adding new messages

Add a new DOM element binding

1
packages/svelte/src/internal/client/dom/elements/bindings/

Create new binding file or add to existing (e.g., input.js for input bindings)

Pattern: See packages/svelte/src/internal/client/dom/elements/bindings/input.js for bind_value pattern with get/set functions

2
packages/svelte/src/internal/client/dom/elements/bindings/index.js

Export the new binding function

Pattern: Add export statement matching existing exports like bind_value, bind_checked

3
packages/svelte/src/compiler/phases/3-transform/client/visitors/BindDirective.js

Add code generation for the new binding type

Pattern: See switch statement in BindDirective.js that maps binding names to runtime calls

4
packages/svelte/src/compiler/phases/2-analyze/visitors/BindDirective.js

Add validation for the new binding if needed

Pattern: Check valid_bindings arrays and validation logic in this file

Conventions to follow:

Binding functions are named bind_<name> (e.g., bind_value, bind_checked)Bindings must handle both initial set and updates via effectsServer-side bindings are no-ops, check packages/svelte/src/internal/server/index.js

Add a new reactive primitive

1
packages/svelte/src/reactivity/

Create new reactive wrapper file (e.g., svelte-weakmap.js)

Pattern: See packages/svelte/src/reactivity/map.js for SvelteMap implementation using source() and get()

2
packages/svelte/src/reactivity/index.js

Export the new reactive class

Pattern: Add export matching existing: export { SvelteMap } from './map.js'

3
packages/svelte/types/index.d.ts

Add TypeScript type definitions for the new reactive class

Pattern: See existing SvelteMap, SvelteSet type definitions in this file

4
packages/svelte/tests/runtime-runes/samples/

Add test case directory with _config.js and main.svelte

Pattern: See packages/svelte/tests/runtime-runes/samples/reactive-map/ for test structure

Conventions to follow:

Reactive classes extend native classes (e.g., SvelteMap extends Map)Use source() for reactive state, get() to read with trackingClass names use Svelte prefix (SvelteMap, SvelteDate, SvelteURL)

Add a new block type (like {#each} or {#if})

1
packages/svelte/src/compiler/phases/1-parse/state/template.js

Add parsing logic for the new block syntax

Pattern: See how each_block and if_block are parsed with open/close tag handling

2
packages/svelte/src/compiler/types/template.d.ts

Add AST node type definition for the new block

Pattern: See EachBlock, IfBlock type definitions with their specific properties

3
packages/svelte/src/compiler/phases/2-analyze/visitors/

Create visitor file for semantic analysis (e.g., NewBlock.js)

Pattern: See packages/svelte/src/compiler/phases/2-analyze/visitors/EachBlock.js for scoping and validation

4
packages/svelte/src/compiler/phases/3-transform/client/visitors/

Create client transform visitor for code generation

Pattern: See packages/svelte/src/compiler/phases/3-transform/client/visitors/EachBlock.js for runtime call generation

5
packages/svelte/src/internal/client/dom/blocks/

Create runtime block implementation

Pattern: See packages/svelte/src/internal/client/dom/blocks/each.js for block lifecycle management

6
packages/svelte/src/compiler/phases/3-transform/server/visitors/

Create server transform visitor for SSR

Pattern: See packages/svelte/src/compiler/phases/3-transform/server/visitors/EachBlock.js

Conventions to follow:

Block AST nodes have type property matching the block nameVisitors are registered in the visitors/index.js for each phaseRuntime blocks export a function that returns a cleanup function

Add a new rune (like $state or $derived)

1
packages/svelte/src/compiler/phases/2-analyze/visitors/CallExpression.js

Add rune detection and validation in the CallExpression visitor

Pattern: See how $state, $derived are detected via is_rune() and validated

2
packages/svelte/src/compiler/phases/3-transform/client/visitors/CallExpression.js

Add client-side code transformation for the rune

Pattern: See how $state transforms to $.state() calls

3
packages/svelte/src/internal/client/reactivity/sources.js

Add runtime implementation if rune creates reactive state

Pattern: See source() and mutable_source() implementations

4
packages/svelte/src/ambient.d.ts

Add TypeScript declarations for the new rune

Pattern: See $state, $derived declarations with overloads

5
packages/svelte/tests/runtime-runes/samples/

Add comprehensive test cases

Pattern: See packages/svelte/tests/runtime-runes/samples/state-basic/ structure

Conventions to follow:

Runes start with $ prefix and are compile-time constructsRunes transform to $.runtime_function() callsRunes must work in both client and server contexts

Add a new transition or animation

1
packages/svelte/src/transition/index.js

Add new transition function export

Pattern: See fade, fly, slide implementations - return object with delay, duration, easing, css/tick

2
packages/svelte/types/index.d.ts

Add TypeScript types for transition parameters and return type

Pattern: See FadeParams, FlyParams interfaces and TransitionConfig return type

3
packages/svelte/tests/runtime-legacy/samples/

Add test with transition usage

Pattern: See packages/svelte/tests/runtime-legacy/samples/transition-js-*/ for test patterns

Conventions to follow:

Transitions return TransitionConfig with css() or tick() functionUse easing functions from packages/svelte/src/easing/index.jsTransitions must handle both in and out directions

Add a new SSR playground endpoint

1
playgrounds/sandbox/ssr-dev.js

Add route handling in the request handler

Pattern: See existing GET /* handler that renders Svelte components

2
playgrounds/sandbox/ssr-prod.js

Add production route handling with static asset support

Pattern: See how / and /*.(js|css) routes are handled separately

Conventions to follow:

Dev server uses Vite for HMR and module loadingProd server serves pre-built assets from dist/client/Both must handle the render() function from compiled Svelte

Add a new benchmark

1
benchmarking/benchmarks/reactivity/

Create new benchmark file for reactivity tests

Pattern: See benchmarking/benchmarks/reactivity/sbench.js for benchmark object structure with setup/run

2
benchmarking/benchmarks/reactivity/index.js

Export new benchmark from the index

Pattern: Add to the exported array of benchmark objects

3
benchmarking/benchmarks/reactivity/util.js

Use utility functions for consistent benchmark creation

Pattern: See create_benchmark helper for standardized test case creation

Conventions to follow:

Benchmarks export objects with name, setup, and run propertiesUse benchmarking/compare/index.js for cross-branch comparisonsSSR benchmarks go in benchmarking/benchmarks/ssr/

Add a new migration rule (Svelte 4 to 5)

1
packages/svelte/src/compiler/migrate/index.js

Add migration transformation logic

Pattern: See existing migrations for reactive statements, slots, event handlers

2
packages/svelte/tests/migrate/samples/

Add test case with input.svelte and output.svelte

Pattern: See packages/svelte/tests/migrate/samples/ for before/after test pairs

Conventions to follow:

Migrations transform Svelte 4 syntax to Svelte 5 runesTest cases have input.svelte (v4) and output.svelte (v5)Preserve formatting and comments where possible

Coding Conventions

Standards and patterns used in this codebase

Code Style

Use tabs for indentation, not spaces. Configure ESLint and Prettier to enforce tab-based indentation across the codebase.

{ "useTabs": true, "tabWidth": 2 }
eslint.config.js
Code Style

Prefer arrow functions and use single quotes for strings. Configure ESLint to enforce consistent function style and quote usage.

rules: { '@stylistic/quotes': ['error', 'single'] }
eslint.config.js
Module System

Use ES modules with explicit .js extensions in imports. Configure module resolution for both Node.js and browser environments.

resolve: { conditions: ['development', 'browser'] }
vitest.config.jsvite.config.js
Testing

Use Vitest as the test framework with jsdom environment. Configure test file patterns and module aliases for internal packages.

export default defineConfig({ plugins: [svelte()], test: { environment: 'jsdom', alias: [{ find: /^svelte\/?/, replacement: `${pkg}/src/` }] } });
vitest.config.js
Build Configuration

Use Rollup for library builds with explicit external dependencies and multiple output formats (esm, cjs). Generate TypeScript declarations alongside JavaScript.

output: { format: 'esm', dir: './types' }, external: ['acorn', 'esrap', 'zimmerframe', 'esm-env', 'locate-character']
packages/svelte/rollup.config.js
SSR Architecture

Separate SSR development and production servers. Use Vite middleware for development with HMR, and static file serving for production builds.

const { createServer } = await import('vite'); const vite = await createServer({ server: { middlewareMode: true } }); app.use(vite.middlewares);
playgrounds/sandbox/ssr-dev.jsplaygrounds/sandbox/ssr-prod.js
Compiler Options

Configure Svelte compiler with explicit runes mode and accessibility warnings. Use modernAst for updated AST format.

compilerOptions: { runes: true, warningFilter: (warning) => !warning.code.startsWith('a11y') }
playgrounds/sandbox/svelte.config.jssvelte.config.js
Performance Testing

Implement benchmarking with Git branch comparison. Measure both execution time and garbage collection metrics, running multiple iterations for statistical validity.

for (let i = 0; i < 20; i++) { const durations = await page.evaluate(async (iterations) => { const times = []; for (let i = 0; i < iterations; i++) { const start = performance.now(); await run(); times.push(performance.now() - start); } return times; }, 100); }
benchmarking/compare/index.js
TypeScript

Provide comprehensive TypeScript definitions for HTML/SVG elements with proper event handler typing and attribute interfaces. Use conditional types for element-specific attributes.

interface HTMLInputAttributes extends HTMLAttributes<HTMLInputElement> { accept?: string | undefined | null; bind:value?: string | number | null; 'on:change'?: ChangeEventHandler<HTMLInputElement> | undefined | null; }
packages/svelte/elements.d.ts
Linting

Disable certain ESLint rules for specific patterns like generated code or test files. Use glob patterns to apply different rules to different file types.

ignores: [ '**/*.d.ts', '**/tests/**/*', 'packages/svelte/src/compiler/errors.js' ]
eslint.config.js