0
0
Svelteframework~15 mins

Script, markup, and style sections in Svelte - Deep Dive

Choose your learning style9 modes available
Overview - Script, markup, and style sections
What is it?
In Svelte, components are made up of three main parts: script, markup, and style sections. The script section holds the JavaScript code that controls the component's behavior. The markup section contains the HTML-like code that defines what the component shows on the screen. The style section includes CSS that styles the component's appearance. These sections work together to build interactive and styled user interfaces.
Why it matters
Without separating script, markup, and style, building user interfaces would be messy and hard to manage. This clear division helps developers organize code so it’s easier to read, update, and reuse. It also allows Svelte to optimize the app by compiling these parts efficiently, making apps faster and smaller. Without this, web apps would be slower and harder to maintain.
Where it fits
Before learning this, you should know basic HTML, CSS, and JavaScript. After mastering these sections, you can learn about Svelte’s advanced features like reactive statements, stores, and component lifecycle. This topic is a foundation for building any Svelte app.
Mental Model
Core Idea
A Svelte component is like a mini webpage where script controls logic, markup defines structure, and style decorates the look, all bundled neatly together.
Think of it like...
Think of a Svelte component like a recipe card: the script is the instructions, the markup is the list of ingredients arranged on the plate, and the style is the decoration that makes the dish look tasty.
┌───────────────┐
│ SvelteComponent│
├───────────────┤
│ ┌───────────┐ │
│ │ <script>  │ │  ← JavaScript logic
│ └───────────┘ │
│ ┌───────────┐ │
│ │ Markup    │ │  ← HTML structure
│ │ (template)│ │
│ └───────────┘ │
│ ┌───────────┐ │
│ │ <style>   │ │  ← CSS styles
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding the script section
🤔
Concept: The script section holds JavaScript code that controls data and behavior inside the component.
Inside a Svelte component, the
Correct approach:
Root cause:Confusing module scope with instance scope, causing shared state bugs.
#3Expecting markup to update when changing a variable without using reactive declarations or assignments.
Wrong approach:

{name}

Correct approach:

{name}

Root cause:Actually, this is correct; the pitfall is when variables are mutated without assignment, e.g., modifying an object property without reassigning the variable, so Svelte doesn’t detect the change.
Key Takeaways
Svelte components have three clear parts: script for logic, markup for structure, and style for appearance.
Script variables automatically update the markup, creating reactive user interfaces without manual DOM work.
Styles inside components are scoped by default, preventing conflicts and keeping UI consistent.
Using