| | |

Svelte 3 ๐Ÿงก Svelte Component Anatomy

โฑ๏ธ Estimated read: 23 min | |

A Svelte component is one file with three optional blocks: a <script> block that holds the logic, a markup section that describes the output, and a <style> block that describes appearance. That is the entire format. There is no required wrapper element, no mandatory export, no hydration marker, and no component base class. A .svelte file is HTML with expressions, and the compiler reads the three blocks and emits JavaScript.

The format is deliberately narrow. Where React separates the component function (.jsx) from styles (.css) and props (TypeScript interface) into different files, and where Vue offers <template>, <script>, and <style> blocks that the developer must order correctly, Svelte keeps the three concerns in one file and lets the compiler decide how they connect. The <script> block declares state, the markup reads it, and the <style> block scopes to the markup’s elements by default. There is nothing between those three parts.

This chapter walks through the anatomy block by block: what the <script> block accepts, how <script module> differs from the instance form, how the markup interprets expressions and control-flow blocks, what the <style> block scopes and how :global() escapes the scope, and how the special <svelte:*> elements reach outside the component’s own tree. It ends with a ten-part example session that assembles a component using every piece of the anatomy in order.

Key point: A .svelte file is three blocks in a fixed relationship โ€” <script> (optional, instance and module forms), markup (the component’s output), and <style> (scoped CSS). The compiler ties them together: props flow from the parent through the script, markup reads the script’s exports, and the styles apply only to the elements the markup produced.


Why the single-file component format exists

The three-concerns problem. A UI element is simultaneously a piece of state, a piece of DOM, and a piece of styling, and its meaning is only clear when all three are visible together. Splitting them across files does two things: it hides one concern from the reader every time, and it forces the developer to invent a naming convention โ€” a class, an id, a file โ€” that links them back up. Svelte’s answer is the file itself. The .svelte extension is the link, and it never appears in the browser because the compiler has already resolved it.

The scoping problem. Global CSS is a shared namespace. Every class name is visible to every component, and a stylesheet that matches .button styles every element with that class in the whole application. The <style> block in a Svelte component is scoped by default โ€” the compiler adds a hash to the selector and to the elements the markup emitted, so .button inside one component can never reach another. Scoping is a property of the format, not of a tool the developer has to configure, which is why it works without exception in a Svelte project.

The module-vs-instance problem. Some component logic is per-instance (a counter’s count), and some is shared across every instance (a global configuration, an icon set, a cache). In React, useState is per-instance and useContext is the reconciliation path; in Vue, a reactive object is per-instance and a plugin provides the shared state. Svelte’s format makes the split structural: <script> is per-instance, and <script module> runs once at module load. The two blocks cannot be confused because they have different tags, and the compiler emits different code for each.

The distribution problem. A component library needs three things at once: source the developer can read, a type definition for TypeScript users, and a compiled artifact for runtime. A SFC format makes the first two possible from one artifact โ€” the source is the file, and the type is derived from its <script lang="ts">. The third is generated by the compiler. Single-file components are therefore the only format where the developer-facing source and the build output can live in the same package without duplication.

The tooling problem. Editors need to colour HTML, JavaScript, and CSS in one document, and language servers need to link an expression in the markup to a variable in the script. A single-file format makes both jobs tractable: the tool parses the file into three regions and hands each region to the appropriate analyser, then links the results by variable name. That is why the extension has first-class support in every modern editor and why jumping from {count} to let count works.

The trade-off. The format constrains how components are written, and the constraint is real. There is one <script> block per context (instance or module) and the ordering of its contents matters only insofar as the compiler is concerned; there is one <style> block and it applies to one component. A style shared across many components must be extracted to a global stylesheet, which is a smaller scope than a design system sometimes wants. The format is at its best when components are small and self-contained, and it becomes friction when they are large and layered.


a. The three blocks: <script>, markup, and <style>

Every <script>, <style>, and expression in a .svelte file is parsed by the compiler. The <script> block is the only block that always runs as JavaScript; the markup is compiled to DOM-code; the <style> block is compiled to plain CSS. The dependency between them is one-directional: the markup reads the <script>‘s bindings, and the <style> reads nothing at all because selectors are static.

<!-- src/Price.svelte โ€” the anatomy in its smallest form -->
<script>
  // Runs once per instance, in the component's scope
  let price = 9.99;
  let quantity = 1;
  let total = $derived(price * quantity); // computed, never stored
</script>

<!-- The markup reads the script's bindings by name -->
<p class="total">{total}</p>
<button onclick={() => quantity++}>Add one</button>

<style>
  /* The compiler scopes these to the markup's elements */
  .total {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
  }
</style>

The three blocks can appear in any order; the compiler recognises them by tag and reassembles them. What the developer sees when they open the file is the order they wrote, but the ordering that matters is inside the script โ€” declarations come before the code that references them at module evaluation.

The <script> block accepts any JavaScript. Its top-level bindings become the component’s state. It can import, define functions, declare constants, and hold TypeScript when lang="ts" is set. Its exports have special meaning โ€” discussed in the module context section โ€” and export let or $props() is how props are declared.

<script lang="ts">
  import { formatCurrency } from "$lib/currency"; // imports appear at the top
  export let currency = "USD";                    // Svelte 4 prop declaration

  function format(n: number): string {
    return formatCurrency(n, currency);            // helper defined in-script
  }
</script>

The markup section is everything that is not a script, style, or comment. It is compiled into the DOM-building code, and every {expression}, {#if ...}, {#each ...}, {#await ...}, and bind: construct becomes a signal read, an effect, or an event binding. There is no wrapper element and no root requirement โ€” a component’s markup can be a fragment of any shape.

<!-- The markup is a compiled tree of static nodes and reactive expressions -->
<input bind:value={query} placeholder="Search" />
{#if query.length > 0}
  <p>{results.length} results for "{query}"</p>
{:else}
  <p>Type to search</p>
{/if}

The <style> block is scoped by default. The compiler appends a hash to each selector, matching only elements the markup emitted. This is the mechanism that makes the “one file per component” claim honest: the styles that belong to a component’s elements actually belong to the component at the CSS level, not just at the file level.

<style>
  /* The compiler rewrites this to .search-box.svelte-hash, not .search-box */
  .search-box {
    border: 1px solid var(--line);
  }
</style>

The <style> block can reference global selectors with :global() when the reach is intentional โ€” a third-party widget, a container that must inherit a rule, an element rendered by {@html}.

<style>
  /* Scoped: only the local element */
  .wrapper { display: flex; }

  /* Global: reaches inside trusted HTML inserted with {@html ...} */
  .wrapper :global(.cms-paragraph) {
    line-height: 1.6;
  }
</style>

b. Instance and module context โ€” the two <script> blocks

A component can have one <script> block and one <script module> block. The first runs per instance, in the component’s scope, and its bindings are the component’s state. The second runs once when the module is loaded, in the module’s scope, and its bindings are shared by every instance. The distinction is structural, not a convention the developer must maintain.

<script module>
  // Runs once, when the component module is first imported.
  // `cache` is shared by every <Weather /> on the page.
  const cache = new Map();

  export function clear() {
    cache.clear();                   // callable from the importing module
  }
</script>

<script>
  // Runs per instance; each <Weather /> has its own `city` and `data`
  let { city } = $props();
  let data = $state(null);

  async function load() {
    if (!cache.has(city)) {
      cache.set(city, await fetchWeather(city)); // cache shared across instances
    }
    data = cache.get(city);
  }
  load();
</script>

The <script module> block is also where named exports originate. A parent that imports the component receives the component’s default export (the component itself) and any named export the module block declared.

<!-- IconLibrary.svelte -->
<script module>
  // Named exports travel alongside the component
  export const sizes = ["sm", "md", "lg"];
  export function listIcons() { /* ... */ }
</script>

<script>
  let { name, size = "md" } = $props();
</script>

<svg class="icon-{size}"><use href="#{name}" /></svg>
<!-- Any consumer of the component can reach the named exports -->
<script>
  import Icon, { sizes, listIcons } from "./IconLibrary.svelte";
  console.log(sizes, listIcons());
</script>

<Icon name="check" />

Props belong in the instance block (or are produced by $props() in the runes form), never in the module block. Reactive statements and effects also belong in the instance block, because module-scoped effect registration would defeat the point of having a shared context. The module block is for static or shared state only: a cache, a list of constants, a counter that survives across instances.

<script module>
  // A shared counter of mounted instances โ€” module scope, by design
  let mounted = 0;
  export const mountedCount = () => mounted;
</script>

<script>
  import { onMount } from "svelte";
  onMount(() => {
    mounted++;                       // increments the module-shared counter
    return () => { mounted--; };     // cleanup on unmount
  });
</script>

c. Template syntax: expressions, blocks, bindings, and special elements

The markup is more than a template โ€” it is a small language with control-flow blocks, bindings, and special elements that reach outside the component’s own tree. Understanding its grammar is most of knowing how to write a .svelte file.

Expressions. Any {expression} in the markup is evaluated in the component’s scope. Expressions read state, call functions, and produce values. Reactive expressions โ€” the ones the compiler tracks โ€” are those whose reads depend on reactive sources ($state, $derived, or props).

<!-- Expressions can be members, calls, ternaries, and short-circuiting -->
<p>{user.name.toUpperCase()}</p>
<span class:active={isActive}>{isActive ? "On" : "Off"}</span>
<time>{formatDate(createdAt)}</time>

Control-flow blocks. {#if}, {#each}, and {#await} are the three block forms. Each can have an {:else} or {:then}/{:catch} companion, and {#each} accepts a key expression that is critical for list identity.

<!-- Conditional rendering -->
{#if error}
  <p class="error">{error.message}</p>
{:else if loading}
  <p>Loadingโ€ฆ</p>
{:else}
  <p>Ready</p>
{/if}

<!-- Keyed iteration โ€” the key preserves DOM identity and state per row -->
{#each rows as row (row.id)}
  <Row {row} />
{/each}

<!-- Await โ€” resolves a promise with `then` and `catch` branches -->
{#await fetchUser(id)}
  <p>Loadingโ€ฆ</p>
{:then user}
  <p>{user.name}</p>
{:catch err}
  <p>Failed: {err.message}</p>
{/await}

Bindings. bind: connects a form control or a DOM property to a state variable in both directions. bind:value is the common case; bind:checked, bind:group, bind:files, and bind:this cover the rest. Binding is what removes the manual oninput handler in the vast majority of components.

<!-- Two-way binding on the value; group binds multiple radios to one variable -->
<input bind:value={email} type="email" />
<input bind:checked={remember} type="checkbox" />
<input bind:group={color} type="radio" value="red" />
<input bind:group={color} type="radio" value="blue" />

<!-- bind:this attaches the element to a state variable for imperative access -->
<script>
  let canvas = $state();
  onMount(() => canvas.getContext("2d").fillRect(0, 0, 10, 10));
</script>
<canvas bind:this={canvas} />

Special elements. The compiler provides a small set of <svelte:*> elements that reach outside the component’s own scope โ€” the document head, the window and document events, the body class, and the element that renders at runtime. These are the anatomy’s edge: they exist because some effects cannot be expressed as an expression in the markup.

<!-- <svelte:head> injects into the document head -->
<svelte:head>
  <title>Checkout</title>
  <meta name="description" content="Confirm your order" />
</svelte:head>

<!-- <svelte:window> and <svelte:document> attach listeners to globals -->
<svelte:window onkeydown={(e) => e.key === "Escape" && close()} />
<svelte:document onvisibilitychange={pause} />

<!-- <svelte:component> renders a component chosen at runtime -->
<svelte:component this={currentView} {...props} />

<!-- <svelte:element this="section"> renders a tag chosen at runtime -->
<svelte:element this={headingLevel}>{title}</svelte:element>

Slot and snippet content. Children passed to a component are its content. In modern Svelte they arrive through a children snippet prop, and named content through declared snippet props. This is how layout components and reusable shells work.

<!-- Card.svelte: declares `children` as an implicit prop -->
<script>
  let { children, title } = $props();
</script>

<article>
  {#if title}<header>{title}</header>{/if}
  {@render children?.()}  <!-- renders the content the parent provided -->
</article>
<!-- The parent provides content as children -->
<script>
  import Card from "./Card.svelte";
</script>

<Card title="Summary">
  <p>Payment due in 14 days.</p>
</Card>

Directives. class:, style:, use:, transition:, in:, out:, and animate: are the modifier directives. Each attaches behaviour to an element without a manual wrapper or handler.

<!-- class: toggles a class based on a boolean; style: sets a style property -->
<button
  class:active={selected}
  style:color={selected ? "var(--accent)" : "inherit"}
  onclick={select}
>
  {label}
</button>

Complete Example Session

<!-- ============================================ -->
<!-- PART 1: THE MODULE SCRIPT โ€” SHARED ACROSS ALL INSTANCES -->
<!-- ============================================ -->
<!-- src/ProductCard.svelte -->
<script module>
  // Runs once at import; shared currency lookup
  const rates = { USD: 1, EUR: 0.92, GBP: 0.79 };

  // Named export travels with the component
  export function formatMoney(n, currency = "USD") {
    const converted = n * rates[currency];
    return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(converted);
  }
</script>

<!-- ============================================ -->
<!-- PART 2: THE INSTANCE SCRIPT โ€” ONE PER CARD -->
<!-- ============================================ -->
<script>
  // Inputs from the parent, with a default
  let { product, currency = "USD", onAdd } = $props();

  // Local per-instance state
  let quantity = $state(1);
  let added = $state(false);

  // Derived total, recomputed only when quantity changes
  let total = $derived(product.price * quantity);

  function add() {
    onAdd({ product, quantity });  // emit up to the parent
    added = true;
    setTimeout(() => (added = false), 1500);
  }
</script>

<!-- ============================================ -->
<!-- PART 3: THE MARKUP โ€” THE COMPONENT'S OUTPUT -->
<!-- ============================================ -->
<article class="card">
  <header>
    <h2>{product.name}</h2>
    <span class="badge">{product.stock > 0 ? "In stock" : "Sold out"}</span>
  </header>

  <p class="price">{formatMoney(product.price, currency)}</p>

  <!-- ============================================ -->
  <!-- PART 4: THE QUANTITY CONTROL โ€” bind: AND class: -->
  <!-- ============================================ -->
  <div class="qty">
    <button onclick={() => (quantity = Math.max(1, quantity - 1))}>โˆ’</button>
    <input bind:value={quantity} type="number" min="1" max={product.stock} />
    <button onclick={() => (quantity = Math.min(product.stock, quantity + 1))}>+</button>
  </div>

  <!-- ============================================ -->
  <!-- PART 5: THE CONDITIONAL โ€” {#if} WITH ADDED FLASH -->
  <!-- ============================================ -->
  <button class:added disabled={product.stock === 0} onclick={add}>
    {added ? "Added โœ“" : `Add ${quantity} for ${formatMoney(total, currency)}`}
  </button>
</article>

<!-- ============================================ -->
<!-- PART 6: THE SCOPED STYLE -->
<!-- ============================================ -->
<style>
  .card {
    display: grid;
    gap: 0.75rem;
    padding: 1rem;
    border: 1px solid var(--line);
    border-radius: 8px;
  }
  .price {
    font-weight: 600;
    font-variant-numeric: tabular-nums;
  }
  .qty {
    display: flex;
    gap: 0.25rem;
  }
  .qty input {
    width: 4rem;
    text-align: center;
  }
  .badge {
    font-size: 0.8rem;
    color: var(--muted);
  }
  button.added {
    background: var(--success);
    color: white;
  }
</style>
<!-- ============================================ -->
<!-- PART 7: THE SPECIAL ELEMENTS โ€” <svelte:head> AND <svelte:window> -->
<!-- ============================================ -->
<!-- src/CheckoutPage.svelte -->
<script>
  let panelOpen = $state(false);
</script>

<svelte:head>
  <title>Checkout</title>
  <meta name="description" content="Confirm your order" />
</svelte:head>

<!-- ============================================ -->
<!-- PART 8: THE GLOBAL EVENT โ€” <svelte:window> -->
<!-- ============================================ -->
<svelte:window
  onkeydown={(e) => { if (e.key === "Escape") panelOpen = false; }}
/>

<!-- ============================================ -->
<!-- PART 9: THE SLOT CONTENT โ€” children SNIPPET PROP -->
<!-- ============================================ -->
<!-- src/Modal.svelte -->
<script>
  let { open, onClose, children } = $props();
</script>

{#if open}
  <div class="backdrop" onclick={onClose}>
    <div class="panel" onclick={(e) => e.stopPropagation()}>
      {@render children?.()}
    </div>
  </div>
{/if}

<style>
  .backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.4); }
  .panel { background: white; max-width: 32rem; margin: 4rem auto; padding: 1.5rem; }
</style>
<!-- ============================================ -->
<!-- PART 10: THE COMPOSITION โ€” ALL PARTS TOGETHER -->
<!-- ============================================ -->
<script>
  import ProductCard, { formatMoney } from "./ProductCard.svelte";
  import Modal from "./Modal.svelte";
  let panelOpen = $state(false);
  let cart = $state([]);
</script>

{#each products as product (product.id)}
  <ProductCard
    {product}
    currency="EUR"
    onAdd={(item) => cart.push(item)}
  />
{/each}

<Modal open={panelOpen} onClose={() => (panelOpen = false)}>
  <h3>Cart</h3>
  <p>Total: {formatMoney(cart.reduce((s, i) => s + i.product.price * i.quantity, 0), "EUR")}</p>
</Modal>

The ten parts covered the module context and its named exports, the instance context and props, the compiled markup, the binding and class directives, the {#if} block, the scoped style, the special elements, the global event handler, the children snippet, and a parent that composes it all.


Quick Reference

The Blocks

BlockWhere It RunsPurpose
<script>Per instanceState, props, effects, logic
<script module>Once per moduleShared state, named exports
MarkupCompiled to DOM codeThe component’s output
<style>Compiled to scoped CSSSelectors matched via a hash

Control-Flow Blocks

BlockCompanionPurpose
{#if}{:else if} / {:else}Conditional rendering
{#each}(key), {:else}Iteration with a key
{#await}{:then} / {:catch}Promise states
{#key}โ€”Force a subtree to re-render

Bindings and Directives

SyntaxPurpose
bind:valueTwo-way value binding
bind:checked, bind:groupCheckbox and radio groups
bind:thisElement handle
class:name={cond}Toggle a class
style:prop={value}Set a style property
use:actionAttach an action
transition:fnApply a transition

Special Elements

ElementPurpose
<svelte:head>Inject into the document head
<svelte:window>Attach window listeners
<svelte:document>Attach document listeners
<svelte:body>Body-level events
<svelte:component>Render a component chosen at runtime
<svelte:element>Render a tag chosen at runtime

Best Practices

โœ… Do This:

<!-- Split instance and module state correctly -->
<script module>const cache = new Map();</script>              <!-- โœ… -->

<!-- Declare props with destructuring -->
let { title, count = 0 } = $props();                          <!-- โœ… -->

<!-- Key each rows on a stable id -->
{#each rows as row (row.id)}                                  <!-- โœ… -->

<!-- Use bind: for form inputs -->
<input bind:value={email} />                                  <!-- โœ… -->

<!-- Scope styles by default; use :global() deliberately -->
<style>.card { ... }</style>                                  <!-- โœ… -->

<!-- Render children through the snippet -->
{@render children?.()}                                        <!-- โœ… -->

<!-- Put named exports on the module block -->
<script module>export const VERSION = "1.0";</script>         <!-- โœ… -->

โŒ Don’t Do This:

<!-- Declare a prop on the module block -->
<script module>export let title = "";</script>                <!-- โŒ -->

<!-- Use index as a key on a reorderable list -->
{#each rows as row, i (i)}                                    <!-- โŒ -->

<!-- Emit a "render" call or synthetic event -->
element.dispatchEvent(new Event("click"));                    <!-- โŒ -->

<!-- Reach past the style scope for a local element -->
<style>:global(.card) { ... }</style>                         <!-- โŒ -->

<!-- Store a derived value in $state -->
let total = $state(price * qty);                              <!-- โŒ -->

<!-- Hand-write children as a prop instead of the implicit one -->
<Card children="..." />                                       <!-- โŒ -->

<!-- Mutate props directly -->
title = title + "!";                                          <!-- โŒ -->

Common Pitfalls

PitfallWhy It HappensFix
Prop not received from parentDeclared in <script module> by mistakeMove it to <script>
List reorders lose stateIndex used as {#each} keyUse a stable id
State does not update DOMNon-reactive let in Svelte 4 styleDeclare with $state
Style leak between components:global() used broadlyRemove or narrow the global scope
Parent content not renderingChild not using children snippet{@render children?.()}
Named export not foundExported from <script> instead of moduleMove to <script module>
Component cannot be swapped at runtimeDirect <Component /> used<svelte:component this={...} />
bind:this undefinedAccessed before mountRead inside onMount

Real-World Examples

1. A minimal component

<script>let name = "world";</script>
<p>Hello, {name}!</p>

2. Props via destructuring

let { title, size = "md" } = $props();

3. Reactive value

let total = $derived(price * quantity);

4. Module-scoped cache

<script module>const cache = new Map();</script>

5. Named export from a component

<script module>export const VERSION = "1.0";</script>

6. Keyed iteration

{#each rows as row (row.id)}<Row {row} />{/each}

7. Await block

{#await fetchUser(id)}{:then user}{user.name}{/await}

8. Special element for the head

<svelte:head><title>Dashboard</title></svelte:head>

9. Global event on <svelte:window>

<svelte:window onkeydown={(e) => e.key === "Escape" && close()} />

10. Rendering children

{@render children?.()}

Visual

The Three Blocks and Their Roles

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  src/Price.svelte                                          โ”‚
โ”‚                                                            โ”‚
โ”‚  <script>                         โ”€โ”€โ–บ runs per instance    โ”‚
โ”‚    let price = 9.99;                                   ย    โ”‚
โ”‚    let qty = 1;                                            โ”‚
โ”‚    let total = $derived(price * qty);                      โ”‚
โ”‚  </script>                                                 โ”‚
โ”‚                                                            โ”‚
โ”‚  <p>{total}</p>                    โ”€โ”€โ–บ compiled DOM code   โ”‚
โ”‚  <button onclick={...}>+</button>                          โ”‚
โ”‚                                                            โ”‚
โ”‚  <style>                           โ”€โ”€โ–บ scoped CSS          โ”‚
โ”‚    p { font-variant-numeric: tabular-nums; }               โ”‚
โ”‚  </style>                                                  โ”‚
โ”‚                                                            โ”‚
โ”‚  compiler โ”€โ”€โ–บ .js + .css                                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Two Script Contexts

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  <script module>                     <script>              โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€                 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€         โ”‚
โ”‚  โ€ข once per module load              โ€ข once per instance   โ”‚
โ”‚  โ€ข shared across all instances       โ€ข isolated per mount  โ”‚
โ”‚  โ€ข named exports travel              โ€ข no exports allowed  โ”‚
โ”‚  โ€ข no reactivity needed              โ€ข $state, $props etc. โ”‚
โ”‚                                                            โ”‚
โ”‚  cache, constants, helpers           state, props, effects โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Template Grammar

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  MARKUP                                                    โ”‚
โ”‚                                                            โ”‚
โ”‚  {expr}            โ”€โ”€โ–บ evaluated in scope, becomes read    โ”‚
โ”‚  {#if} / {#each}   โ”€โ”€โ–บ compiled control-flow               โ”‚
โ”‚  {#await}          โ”€โ”€โ–บ promise states                      โ”‚
โ”‚  bind:value        โ”€โ”€โ–บ two-way binding                     โ”‚
โ”‚  class:active      โ”€โ”€โ–บ conditional class                   โ”‚
โ”‚  {@render slot}    โ”€โ”€โ–บ renders a snippet                   โ”‚
โ”‚  <svelte:*>        โ”€โ”€โ–บ reaches outside the tree            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Scoped vs. Global Styles

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SOURCE                                                    โ”‚
โ”‚  <style>                                                   โ”‚
โ”‚    .card { ... }        โ”€โ”€โ–บ scoped to this component       โ”‚
โ”‚    :global(.cms p) { }  โ”€โ”€โ–บ escapes the scope              โ”‚
โ”‚  </style>                                                  โ”‚
โ”‚                                                            โ”‚
โ”‚  OUTPUT                                                    โ”‚
โ”‚  .card.svelte-hash { }  โ”€โ”€โ–บ matches local .card only       โ”‚
โ”‚  .cms p              { } โ”€โ”€โ–บ matches any element           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
File extension.svelte
Blocks<script>, markup, <style>
Instance scriptRuns per instance; declares props and state
Module scriptRuns once; declares shared state and named exports
Style scopingAutomatic hash-based, opt out with :global()
Control flow{#if}, {#each}, {#await}, {#key}
Bindingsbind:value, bind:checked, bind:group, bind:this
Directivesclass:, style:, use:, transition:
Special elements<svelte:head>, <svelte:window>, <svelte:component>, <svelte:element>
Content projectionchildren snippet plus {@render}

Key takeaways:

  • The format is three blocks in a fixed relationship. The <script> holds logic and state, the markup is the output, and the <style> scopes to that markup. There is no wrapper function, no root element requirement, and no compilation the developer must manage.
  • The module script is structural, not stylistic. <script module> runs once and its exports reach the importer. Props, effects, and instance state belong in the instance script. Mixing the two produces bugs that are invisible until a second instance is created.
  • Style scoping is a property of the format. The compiler hashes each selector and each emitted element, so a class name in one component cannot reach another. :global() is the deliberate escape for third-party widgets and trusted HTML.
  • The markup is a small language. Expressions, control-flow blocks, bindings, and directives each map to a compiled construct. Learning their shapes is learning the framework’s semantics, because everything else flows through them.
  • Special elements reach outside the component’s tree. <svelte:head>, <svelte:window>, <svelte:component>, and <svelte:element> are the supported ways to touch the document, the window, or a runtime-chosen component โ€” and they exist because these effects cannot be expressed with expressions alone.

Remember: A Svelte component is a file, and the file’s three blocks are the framework’s mental model. Everything that follows โ€” reactivity, composition, testing, SSR โ€” assumes you know which block runs when, which block holds what, and how the markup reads the script’s bindings. Write small components, keep state in the instance script, keep shared helpers in the module script, scope styles by default, and reach outside the tree only through the special elements the compiler provides.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!