0
0
Svelteframework~3 mins

Why Script, markup, and style sections in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how keeping your code's parts neatly separated can make building web apps feel like a breeze!

The Scenario

Imagine building a web page where you write your JavaScript, HTML, and CSS all mixed together in one big file or scattered in separate files without clear organization.

Every time you want to change something, you have to hunt through the code to find where the logic, the structure, or the look is defined.

The Problem

This messy approach makes your code hard to read and maintain.

It's easy to accidentally break something because the parts are tangled.

Also, browsers don't understand this mix well, so you need extra tools to bundle and fix it.

The Solution

Svelte solves this by letting you write your script (logic), markup (HTML), and style (CSS) in clear separate sections inside one file.

This keeps your code neat, easy to understand, and ready to turn into fast web pages.

Before vs After
Before
<script>function greet() { alert('Hi'); }</script><div onclick="greet()">Click me</div><style>div { color: red; }</style>
After
<script>function greet() { alert('Hi'); }</script>
<div on:click={greet}>Click me</div>
<style>div { color: red; }</style>
What It Enables

It enables you to build interactive web components that are easy to write, style, and maintain all in one place.

Real Life Example

Think of a button on a website that changes color when clicked and shows a message. With Svelte's sections, you write the button's look, behavior, and style together clearly.

Key Takeaways

Separate script, markup, and style keep code organized.

Improves readability and maintenance.

Makes building interactive components simpler and faster.