Svelte 4 ๐งก Component Script Blocks, HTML Markup, and CSS Style Scope
A Svelte 4 component is a single .svelte file with three regions: the <script> block, the markup region, and the <style> block. Each region is processed by the compiler in a different way, and each has its own precise semantics. The <script> block holds JavaScript that runs per instance (and a separate <script context="module"> that runs once). The markup region compiles to DOM-building and DOM-updating code, using Svelte 4’s directive syntax. The <style> block is scoped by default: the compiler rewrites every selector with a hash that matches only the elements this component emitted.
Svelte 4 is the last major version before the runes system. It uses export let for props, $: labels for reactive statements, on:event for event handlers, and <slot> for content projection. Those forms are still what most published Svelte code uses, and they are the model every later iteration was designed against. This chapter treats them as the whole โ the script block’s props, reactive statements, lifecycle hooks, and stores; the markup’s expressions, blocks, directives, and special tags; and the style block’s scope, its :global() escape, and its preprocessing options.
The chapter is organised as three deep sections โ one for each region โ followed by a complete example that assembles a working component from every feature the three sections covered.
Key point: The three regions have three distinct contracts. The <script> block runs per instance and exports props with export let; the markup compiles expressions, blocks, and directives into minimal DOM operations; the <style> block scopes selectors to the component’s own elements via a compile-time hash, and :global() is the only way to escape that scope.
Why the three-region split exists
The scope problem. A component is a bounded unit of state, output, and appearance. In a format that keeps those three concerns in separate files, the boundary is a naming convention maintained by hand โ every new component is a chance to leak a class into a global namespace or to import the wrong stylesheet. In a Svelte file the boundary is the file. The script’s let bindings are private until they are exported. The style’s selectors are scoped until :global() is applied. The markup is the only public surface, and it exposes nothing at runtime.
The reactivity problem. A reactive framework has to answer, on every state change, which parts of the output depend on which piece of state. Most frameworks do this at runtime by re-running components and comparing output. Svelte 4 does it at build time: the $: label is a compile-time marker, and the compiler wires every $: statement to the state it reads, and every markup expression to the state it mentions. The compiler infers a dependency graph from the source and emits the update functions accordingly. That is why $: and not useEffect โ the label is a declaration of dependency, not a scheduling call.
The style-scoping problem. CSS has one namespace. A rule that matches .btn matched everywhere. Component-based frameworks have three answers: CSS-in-JS (runtime cost), CSS modules (a build tool convention), or scoping at compile time. Svelte 4 chooses the third. The compiler rewrites each selector to include a class derived from the file path, and adds the same class to every element the markup emitted. The result is that a .btn in Button.svelte can never reach a .btn in Nav.svelte, and that no runtime machinery is needed to enforce the boundary.
The escaping-Hatch problem. Real components need to depart the framework’s default in specific ways: render trusted HTML returned from a CMS, style a child rendered by a third-party widget, project content passed as children, invoke an imperative library on a canvas element. Each escape is a specific syntax โ {@html}, :global(), <slot>, bind:this. They exist as named features because the alternative is a runtime that can be bypassed arbitrarily, which would defeat the compile-time model.
The trade-off. The trade is flexibility for analysis. Component-scoped CSS is safe by default and awkward when a design system genuinely wants shared styles โ which is why Svelte has :global() and why design systems typically ship a global stylesheet alongside component styles. Similarly, export let is a simpler prop model than a $props() rune, but it has no clean way to express defaults that depend on other props or to destructure with types. The format is opinionated, and the opinions are narrow enough to be learnable in an afternoon.
a. The <script> block โ instance scope and module scope
The instance <script> runs once per component instance. It declares the component’s state, its props, its reactive statements, its lifecycle hook registrations, and its helpers. Anything declared there is private to the instance unless exported as a prop.
Props are declared with export let. The export makes the binding a public input; the let gives it a default value that applies when the parent does not supply one. The compiler replaces the declaration with the input-binding logic and drops the default unless the prop is unset.
<script>
// Public inputs โ `export let` is Svelte 4's prop syntax
export let label; // required: no default
export let size = "md"; // optional: default applies when unset
export let disabled = false; // boolean input, defaults to false
// Private state โ no export, so it is not reachable from the parent
let focused = false;
let id = `field-${Math.random().toString(36).slice(2, 9)}`;
</script>
<label>
<input
{id}
{disabled}
on:focus={() => (focused = true)}
on:blur={() => (focused = false)}
/>
<span class:active={focused}>{label}</span>
<small>{size}</small>
</label>
Reactive statements are the $: labels. A statement labelled with $: re-runs whenever the values it reads change. The compiler analyses the reads and connects the assignment to those inputs; the developer does not have to declare dependencies.
<script>
export let price = 0;
export let quantity = 1;
export let taxRate = 0.2;
// Re-runs when `price`, `quantity`, or `taxRate` changes
$: subtotal = price * quantity; // a derived value
$: tax = subtotal * taxRate; // depends on subtotal, therefore transitive
$: total = subtotal + tax;
// A labelled block can contain multiple statements
$: {
if (quantity < 1) quantity = 1; // clamp โ writes state, so reads it too
console.log("recalculating", quantity);
}
</script>
Lifecycle hooks are functions from svelte that register work at specific points. onMount runs after the component is inserted into the DOM and is the correct place for imperative setup (canvas, chart, third-party widget). beforeUpdate and afterUpdate run around each update. onDestroy runs at cleanup. tick returns a promise that resolves after the next update flushes, useful when the code must read from the DOM after state has changed.
<script>
import { onMount, onDestroy, afterUpdate, tick } from "svelte";
let canvas;
let chart;
onMount(() => {
chart = new Chart(canvas); // imperative setup after DOM exists
return () => chart.destroy(); // cleanup if the component unmounts
});
onDestroy(() => {
window.removeEventListener("resize", onResize);
});
afterUpdate(async () => {
await tick(); // wait for the DOM to reflect the latest state
chart.resize(); // then measure it
});
function onResize() { chart?.resize(); }
</script>
Stores are the Svelte 4 mechanism for shared reactivity across components. A store is any object with a subscribe method; the compiler turns $storeName into a subscription that auto-unsubscribes on unmount. writable, readable, and derived from svelte/store are the built-in constructors.
<script>
import { writable, derived } from "svelte/store";
const count = writable(0); // a store with set/update/subscribe
const doubled = derived(count, ($c) => $c * 2); // a store derived from count
function increment() {
count.update((n) => n + 1); // updates the store, not a local variable
}
</script>
<!-- The `$` prefix auto-subscribes; the component unsubscribes on unmount -->
<p>{$count} ร 2 = {$doubled}</p>
<button on:click={increment}>+</button>
The module-context script runs once, when the module is first imported. Its bindings are shared across every instance, and its named exports travel with the component alongside the default export. It is the right place for caches, shared constants, and helpers that do not need reactive state.
<script context="module">
// Runs once, when this component's module is imported
const cache = new Map();
// Named exports become importable alongside the component
export function clearCache() {
cache.clear();
}
export const VERSION = "1.0.0";
</script>
<script>
export let city;
let data;
$: if (city) {
if (!cache.has(city)) {
cache.set(city, fetchWeather(city)); // cache is shared across every instance
}
data = cache.get(city);
}
</script>
Props belong in the instance script, never in the module script. Reactive statements and lifecycle hooks also belong in the instance script. The module script is for static or shared state only โ anything else and the shared scope defeats the point of the component boundary.
b. The HTML markup โ expressions, blocks, and directives
The markup is the compiled output region. Any {expression} there is evaluated in the component’s scope; state reads become signal reads; state writes through the markup (in bind: or event handlers) become signal writes. The grammar has four categories: expressions, block constructs, directive attributes, and special tags.
Expressions are {...} interpolations. They support any JavaScript that evaluates to a value, including member access, function calls, and short-circuiting.
<p>{user.name.toUpperCase()}</p>
<span class:active={isActive}>{isActive ? "Online" : "Offline"}</span>
<time datetime={createdAt.toISOString()}>{formatRelative(createdAt)}</time>
<img src={user.avatar ?? "/default.png"} alt={user.name} />
Control-flow blocks are {#if}, {#each}, {#await}, and {#key}. Each has a specific companion structure. {#if} accepts {:else if} and {:else} chains. {#each} accepts an indexed form (as item, i), a keyed form (as item (item.id)), and an {:else} branch that renders when the list is empty.
{#if error}
<p class="error">{error.message}</p>
{:else if loading}
<p>Loadingโฆ</p>
{:else}
<p>Loaded {items.length} items</p>
{/if}
<!-- Keyed iteration โ the key preserves DOM identity and per-row state -->
{#each items as item (item.id)}
<Row {item} />
{:else}
<p>No items</p>
{/each}
{#await} renders a promise through its lifecycle. The full form has three branches: the pending state, the resolved value, and the rejection. The shorthand form uses only {:then}.
{#await fetchUser(id)}
<Spinner />
{:then user}
<h2>{user.name}</h2>
{:catch err}
<p>Failed: {err.message}</p>
{/await}
{#key} destroys and recreates a subtree when its expression changes. It is the way to force a component to re-initialise with new state, or to re-trigger an in-transition.
<!-- Re-mount the editor when `mode` changes, so its internal state resets -->
{#key mode}
<Editor {mode} />
{/key}
Directive attributes are modifiers that attach behaviour to an element without a manual wrapper or handler. on: binds events, bind: connects two-way values, class: toggles a class from a boolean, style: sets a style property, use: attaches an action, and transition:/in:/out:/animate: attach motion.
<script>
let value = "";
let checked = false;
let color = "red";
function autofocus(node) { // an action: called on mount, may return destroy
node.focus();
return { destroy() { node.blur(); } };
}
</script>
<input
bind:value <!-- two-way value binding -->
class:filled={value.length > 0} <!-- toggle a class from a boolean -->
style:border-color={checked ? "green" : "red"} <!-- set a single style property -->
on:input={() => console.log(value)} <!-- event handler -->
use:autofocus <!-- action called on mount -->
/>
<input type="checkbox" bind:checked />
bind:group is a special form for radios and checkboxes that share a state variable. bind:this attaches an element or component instance to a variable so it can be used imperatively.
<input type="radio" bind:group={color} value="red" />
<input type="radio" bind:group={color} value="blue" />
<canvas bind:this={canvas}></canvas>
Special tags are the escape hatches. {@html raw} renders a trusted HTML string as markup โ it must not be used with user input. {@debug value} logs to the console with a breakpoint when a value changes in development. {@const x = expr} declares a local name inside a block. The <svelte:*> elements reach outside the component’s tree โ <svelte:head> for the document head, <svelte:window> and <svelte:document> for global events, <svelte:component> and <svelte:element> for runtime-chosen components and tags.
<svelte:head>
<title>Dashboard</title>
</svelte:head>
<svelte:window on:keydown={(e) => e.key === "Escape" && close()} />
{@html trustedCmsBody}
{#each rows as row}
{@const total = row.price * row.quantity} <!-- local name for the block -->
<p>{total}</p>
{/each}
<svelte:component this={currentView} {props} />
Content projection uses <slot>. A child component declares a slot with <slot> (default) or <slot name="header"> (named). The parent fills those slots by providing content, and the child can access the slot’s props through let:.
<!-- Card.svelte: declares the slot and passes slot props -->
<article>
<header><slot name="title" {title} /></header>
<div><slot /></div>
</article>
<!-- Parent: fills the slots and destructures the slot props -->
<Card>
<h2 slot="title" let:title>{title}</h2>
<p>Body content</p>
</Card>
Svelte 4 also has createEventDispatcher for component-emitted events, svelte:options for per-file configuration, and svelte:fragment for slot content that must not add a wrapper element.
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch("select", { id: 1 })}>Select</button>
<!-- In the parent: <Child on:select={(e) => console.log(e.detail)} /> -->
c. The <style> block โ scope, escapes, and preprocessors
The <style> block is scoped by default. The compiler appends a class derived from the file path to each selector and to each element the markup emitted. The scoping happens at compile time, so the CSS that ships to the browser has the hash already applied and no runtime mechanism is needed to enforce the boundary.
<!-- src/Button.svelte -->
<button class="primary">Click</button>
<style>
/* Compiled to .primary.svelte-abc123 */
.primary {
background: var(--accent);
color: white;
}
/* Compiled to button.svelte-abc123 โ matches only this component's buttons */
button {
padding: 0.5rem 1rem;
}
</style>
The escape hatch is :global(). Wrapping a selector in :global() makes it match the whole document. :global as a combinator (no parentheses) makes everything after it global while keeping the ancestor scoped โ this is the form to use when a component needs to style descendants of a container that the component owns.
<style>
/* Fully global: matches any .cms-paragraph in the document */
:global(.cms-paragraph) {
line-height: 1.6;
}
/* Scoped ancestor, global descendant: rules only apply inside .content */
.content :global(p) {
margin: 0 0 1em;
}
</style>
The compiler prunes selectors that do not match anything in the markup, which is why an unused class in <style> produces no output. This is a feature โ dead styles cost nothing โ but it surprises developers who expect a <style> block to behave like a plain stylesheet. If a selector must survive without matching an element in the markup (because a child component renders it, or because it applies to {@html} content), it must be wrapped in :global().
<style>
/* This selector survives because it is global โ the compiler cannot know the child's markup */
:global(.markdown-body table) {
border-collapse: collapse;
}
</style>
{@html markdownHtml}
CSS custom properties pass through scoping. A component can declare a variable on its root, and its children can read it, because the cascade is not affected by the hash. This is the mechanism that allows theming without a runtime theming system.
<!-- Theme values declared here cascade into child components -->
<div class="wrapper" style:--accent={themeColor}>
<slot />
</div>
<style>
.wrapper {
--accent: rebeccapurple; /* default; overridden by style: above */
}
.wrapper :global(button) {
background: var(--accent); /* children inherit the custom property */
}
</style>
Preprocessors are configured per-project, not per-file. Once svelte-preprocess is in the build (via Vite’s vitePlugin config), the <style> block accepts lang="scss", lang="postcss", or lang="less". The same applies to <script lang="ts"> and to <template lang="pug">.
<!-- Requires svelte-preprocess in the build; otherwise the lang is ignored -->
<style lang="scss">
$radius: 8px;
.card {
border-radius: $radius;
&:hover { border-color: var(--accent); }
}
</style>
Style and markup are still connected by the compiler. A class added conditionally with class:active={x} is scoped the same as one written literally, because the compiler sees both forms as they are emitted. A class added by {@html} or by a child component is not scoped to this file, and must be styled with :global() or from the child’s own <style> block.
Complete Example Session
<!-- ============================================ -->
<!-- PART 1: THE MODULE CONTEXT โ SHARED STATE -->
<!-- ============================================ -->
<!-- src/CartLine.svelte -->
<script context="module">
// Runs once, on import; shared across every CartLine instance
const priceFormat = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
// Named export travels with the component
export function formatPrice(n) {
return priceFormat.format(n);
}
</script>
<!-- ============================================ -->
<!-- PART 2: THE INSTANCE SCRIPT โ PROPS AND STATE -->
<!-- ============================================ -->
<script>
import { createEventDispatcher, onMount } from "svelte";
// Public inputs โ `export let` with defaults for the optional ones
export let product;
export let quantity = 1;
export let editable = true;
// Private per-instance state
let input;
let mounted = false;
// Component-emitted events travel up through the dispatcher
const dispatch = createEventDispatcher();
</script>
<!-- ============================================ -->
<!-- PART 3: THE REACTIVE STATEMENTS โ $: LABELS -->
<!-- ============================================ -->
<script>
// These re-run whenever the values they read change
$: lineTotal = product.price * quantity; // derived
$: disabled = quantity < 1 || quantity > product.stock; // derived from two reads
$: if (quantity > product.stock) { // side effect inside a label
dispatch("overstock", { product, quantity });
}
// ============================================
// PART 4: THE LIFECYCLE HOOKS
// ============================================
onMount(() => {
mounted = true;
if (editable) input?.focus(); // imperative setup after DOM exists
return () => { mounted = false; }; // cleanup on unmount
});
</script>
<!-- ============================================ -->
<!-- PART 5: THE MARKUP โ EXPRESSIONS AND BLOCKS -->
<!-- ============================================ -->
<article class="line">
<header>
<h3>{product.name}</h3>
<span class="price">{formatPrice(product.price)}</span>
</header>
{#if editable}
<!-- ============================================ -->
<!-- PART 6: THE BINDINGS AND DIRECTIVES -->
<!-- ============================================ -->
<div class="controls">
<button on:click={() => (quantity = Math.max(1, quantity - 1))}>โ</button>
<input
bind:value={quantity}
bind:this={input}
type="number"
min="1"
max={product.stock}
class:invalid={disabled}
/>
<button on:click={() => (quantity = Math.min(product.stock, quantity + 1))}>+</button>
</div>
<p>Line total: {formatPrice(lineTotal)}</p>
{:else}
<p>Quantity: {quantity}</p>
{/if}
<!-- ============================================ -->
<!-- PART 7: THE AWAIT BLOCK -->
<!-- ============================================ -->
{#await fetchAvailability(product.id)}
<p>Checking stockโฆ</p>
{:then available}
<p class:in-stock={available}>{available ? "In stock" : "Sold out"}</p>
{:catch err}
<p class="error">{err.message}</p>
{/await}
</article>
<!-- ============================================ -->
<!-- PART 8: THE SCOPED STYLE -->
<!-- ============================================ -->
<style>
.line {
border: 1px solid var(--line);
padding: 1rem;
border-radius: 8px;
display: grid;
gap: 0.5rem;
}
.controls {
display: flex;
gap: 0.25rem;
}
.controls input {
width: 4rem;
text-align: center;
}
/* Scoped: sets the invalid style for this component's inputs only */
.controls input.invalid {
border-color: var(--danger, red);
}
/* Scoped ancestor, global descendant: only children of .line are styled */
.line :global(.badge) {
font-size: 0.8rem;
color: var(--muted);
}
/* Scoped with a hash: compiles to .in-stock.svelte-xxxxx */
.in-stock {
color: var(--success, green);
}
</style>
<!-- ============================================ -->
<!-- PART 9: THE SLOT PROJECTION โ PARENT USES THE CHILD -->
<!-- ============================================ -->
<!-- src/Checkout.svelte -->
<script>
import CartLine, { formatPrice } from "./CartLine.svelte";
let items = [
{ product: { id: 1, name: "Keyboard", price: 89, stock: 5 }, quantity: 1 },
{ product: { id: 2, name: "Mouse", price: 39, stock: 0 }, quantity: 2 },
];
$: grandTotal = items.reduce((s, i) => s + i.product.price * i.quantity, 0);
function handleOverstock(event) {
console.warn("Overstock:", event.detail);
}
</script>
{#each items as item (item.product.id)}
<CartLine
{...item}
on:overstock={handleOverstock}
/>
{/each}
<footer>
<strong>Total: {formatPrice(grandTotal)}</strong>
</footer>
<!-- ============================================ -->
<!-- PART 10: THE SPECIAL ELEMENTS AND ESCAPES -->
<!-- ============================================ -->
<!-- src/Layout.svelte -->
<script>
let showMenu = false;
let body = $page?.data?.body ?? "";
</script>
<svelte:head>
<title>Storefront</title>
<meta name="description" content="Buy quality accessories" />
</svelte:head>
<svelte:window on:keydown={(e) => e.key === "Escape" && (showMenu = false)} />
<header>
<button on:click={() => (showMenu = !showMenu)}>Menu</button>
</header>
{#if showMenu}
<nav><slot name="menu" /></nav>
{/if}
<main>
<slot />
{@html body}
</main>
<style>
main :global(.markdown) {
max-width: 65ch;
line-height: 1.6;
}
</style>
The ten parts covered the module context and its named exports, the instance script with props, lifecycle hooks, and event dispatch, the reactive $: statements including a side-effect label, the markup expressions and control-flow blocks, the bindings and directives, the await block for a promise, the scoped style plus a :global() descendant rule, the parent that composes the child through slots and events, and the special elements that reach outside the component’s tree.
Quick Reference
The Two Script Contexts
| Form | Runs | Shared With |
|---|---|---|
<script> | Per instance | Nothing โ instance scope |
<script context="module"> | Once per module | Every instance, via module scope |
export let name | Prop declaration | Parent, through the component tag |
$: expr = ... | Reactive statement | Nothing โ re-runs on reads |
$store | Store subscription | Auto-unsubscribed on unmount |
Markup Blocks
| Block | Companions | Purpose |
|---|---|---|
{#if} | {:else if} / {:else} | Conditional rendering |
{#each} | (key), {:else}, as item, i | Iteration |
{#await} | {:then} / {:catch} | Promise states |
{#key} | โ | Re-mount a subtree |
Directives and Special Tags
| Syntax | Purpose |
|---|---|
on:event={fn} | Attach an event listener |
bind:value / bind:group / bind:this | Two-way bindings |
class:name={cond} | Toggle a class |
style:prop={value} | Set a style property |
use:action | Attach an action |
transition:fn / in: / out: / animate: | Motion |
{@html raw} | Insert trusted HTML |
{@debug value} | Dev-only breakpoint |
{@const x = expr} | Local name |
<svelte:head> / <svelte:window> / <svelte:component> | Extra-tree access |
CSS Scope Rules
| Selector | Scope | Notes |
|---|---|---|
.card { } | Component only | Compiled with a hash |
:global(.card) { } | Document | Matches everywhere |
.parent :global(.child) | Scoped ancestor, global child | Common for child styles |
li:global(:first-child) | Scoped element, global state | Combinator form |
--var: value | Cascade-through | Custom properties pass scope |
Best Practices
โ Do This:
<!-- Declare props with `export let` and defaults -->
export let size = "md"; <!-- โ
-->
<!-- Use `$:` for derived values, not lifecycle hooks -->
$: total = price * qty; <!-- โ
-->
<!-- Use `$store` for shared state, not a prop chain -->
$: user = $session.user; <!-- โ
-->
<!-- Read module-shared state from `<script context="module">` -->
<script context="module">const cache = new Map();</script> <!-- โ
-->
<!-- Bind form values to a state variable -->
<input bind:value={email} /> <!-- โ
-->
<!-- Use :global() as a combinator for descendants of your own markup -->
.wrapper :global(p) { margin: 0; } <!-- โ
-->
<!-- Use bind:this for imperative DOM access -->
<canvas bind:this={canvas}></canvas> <!-- โ
-->
โ Don’t Do This:
<!-- Put a prop in the module script -->
<script context="module">export let title = "";</script> <!-- โ -->
<!-- Expect `let` reactivity without a `$:` label -->
let total = price * qty; <!-- โ -->
<!-- Reach the whole document with a bare :global() when you meant a descendant -->
:global(.card) { } <!-- โ -->
<!-- Use {@html} with untrusted content -->
{@html userInput} <!-- โ -->
<!-- Use index as the key on a reorderable list -->
{#each rows as row, i (i)} <!-- โ -->
<!-- Style a child component with a scoped selector -->
.some-child-widget { } /* compile-time prune: no match */ <!-- โ -->
<!-- Attach an event handler with addEventListener inside a component tag -->
on:click="addEventListener(...)" <!-- โ -->
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Prop not received | Declared in <script context="module"> | Move to instance <script> |
let reactivity does not fire | No $: label | Add $: before the binding |
$: runs in an unexpected order | Reads another $: that is later | Reorder or use a labelled block |
| Style has no effect | Selector pruned by the compiler | Wrap in :global() |
| Child styles not applied | Scoped selector cannot reach the child | Style inside the child or :global() |
| Store unsubscribe fails | $store used inside a $: block that never runs | Subscribe in the instance script |
| Slot content not shown | No <slot> in the child | Add <slot> and <slot name="โฆ"> |
bind:this undefined | Accessed before mount | Read inside onMount |
Real-World Examples
1. Declaring props with defaults
export let size = "md";
export let disabled = false;
2. A reactive derived value
$: total = price * quantity;
3. A reactive side effect
$: if (query.length > 2) results = search(query);
4. A module-scoped cache
<script context="module">const cache = new Map();</script>
5. A named export
<script context="module">export const VERSION = "1";</script>
6. Keyed iteration
{#each rows as row (row.id)}<Row {row} />{/each}
7. A two-way binding
<input bind:value={email} type="email" />
8. A scoped style with a global descendant
<style>
.content :global(p) { margin: 0 0 1em; }
</style>
9. An imperative handle via bind:this
<script>
import { onMount } from "svelte";
let canvas;
onMount(() => canvas.getContext("2d").fillRect(0, 0, 10, 10));
</script>
<canvas bind:this={canvas} />
10. A component event
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch("select", { id: 1 })}>Select</button>
Visual
The Three Regions and Their Contracts
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ src/CartLine.svelte โ
โ โ
โ <script context="module"> โโโบ once per module โ
โ const cache = new Map(); โ
โ export function helper() {} โ
โ </script> โ
โ โ
โ <script> โโโบ once per instance โ
โ export let product; โ
โ let qty = 1; โ
โ $: total = product.price * qty; โ
โ onMount(() => { /* โฆ */ }); โ
โ </script> โ
โ โ
โ <article>{product.name}</article> โโโบ compiled DOM code โ
โ โ
โ <style> โโโบ hashed CSS โ
โ .line { } โ .line.svelte-x1y2z โ
โ :global(.cms p) โ .cms p โ
โ </style> โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Instance vs Module Split
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ <script context="module"> <script> โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโ โ
โ โข runs on first import โข runs on mount โ
โ โข shared by every instance โข isolated per instance โ
โ โข named exports travel โข props, state, hooks โ
โ โข no reactive `$:` needed โข `$:` labels active โ
โ โ
โ use for: caches, constants, use for: props, state, โ
โ helper functions lifecycle โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
CSS Scope Resolution
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SOURCE SELECTOR EMITTED SELECTOR โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ .card .card.svelte-x1y2z โ
โ button button.svelte-x1y2z โ
โ :global(.cms) .cms โ
โ .content :global(p) .content.svelte-x1y2z p โ
โ :global(.a) .b .a .b.svelte-x1y2z โ
โ โ
โ selectors with NO match in the markup are pruned โ
โ unless they contain `:global` โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Reactive $: Dependency Graph
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ export let price โ
โ export let qty โ
โ โ โ
โ โโโโโโโโโโโโบ $: subtotal = price * qty โ
โ โ โ โ
โ โ โผ โ
โ โ $: tax = subtotal * rate โ
โ โ โ โ
โ โ โผ โ
โ โ $: total = subtotal + tax โ
โ โ โ โ
โ โ โผ โ
โ โ markup reads {total} โ
โ โ โ
โ โโโโโโโโโโโโบ {price} in the markup โ
โ โ
โ the compiler inferred each edge; no manual dependency listโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| File extension | .svelte |
| Instance script | <script> โ runs per instance |
| Module script | <script context="module"> โ runs once |
| Prop declaration | export let name = default |
| Reactive statements | $: labels |
| Store access | $store prefix |
| Markup blocks | {#if}, {#each}, {#await}, {#key} |
| Directives | on:, bind:, class:, style:, use:, transition: |
| Escape tags | {@html}, {@debug}, {@const}, <svelte:*> |
| CSS scope | Hash-based, opt out with :global() |
Key takeaways:
- The two script contexts have distinct contracts. The instance script runs per instance and holds props, reactive statements, lifecycle hooks, and local state. The module script runs once and holds shared caches, constants, and named exports. A prop declared in the wrong block is invisible to the parent, and a cache declared in the wrong block is duplicated per instance.
export letis the prop model. There is no$props()and no destructurable rune in Svelte 4. Theexportprefix makes a binding public; the default value applies when the parent does not supply one.$:labels are dependency declarations. A labelled statement re-runs whenever the values it reads change; the compiler infers the edges. A plainletwith no$:label is not reactive to other variables, and dependencies are the compiler’s business, not the developer’s.- The markup is a compiled grammar. Expressions, blocks, directives, and special tags each map to a specific compile-time construct. Learning these shapes is learning the framework, because there is no runtime template system to reason about.
- Styles are scoped by default and escape only through
:global(). The compiler rewrites selectors with a hash and prunes those that do not match anything in the markup.:global()as a prefix makes a selector global;:globalas a combinator keeps the ancestor scoped while releasing the descendant. - Escapes have specific names.
{@html}for trusted HTML,:global()for out-of-scope styles,<slot>for content projection,bind:thisfor imperative access. They exist as named features because ad-hoc escapes would defeat the compile-time analysis that the rest of the framework depends on.
Remember: A Svelte 4 component is a file with three regions whose contracts are strict. Write props with export let and default them at declaration; express derived values with $: and let the compiler wire the dependencies; keep shared state in the module script so it survives across instances; and treat the <style> block as scoped by default with :global() as the only exception. The framework is small because each region does one thing, and the smallness is what makes the compiled output readable, the bundle small, and the mental model stable.
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!