.svelte files using a superset of HTML.
Component Anatomy
A Svelte component consists of three optional sections:The Script Block
The<script> block contains JavaScript (or TypeScript with lang="ts") that runs when a component instance is created.
1
Variables and State
2
Variables declared at the top level can be referenced in the component’s markup. Use the
$state rune to create reactive state:3
<script>
let count = $state(0);
let items = $state([]);
</script>
4
Imports
5
Import other components, utilities, and Svelte functions:
6
<script>
import { onMount, tick } from 'svelte';
import Button from './Button.svelte';
import { formatDate } from './utils.js';
</script>
7
Functions
8
Define functions that can be called from your markup:
9
<script>
let name = $state('');
function greet() {
alert(`Hello ${name}!`);
}
</script>
<input bind:value={name} />
<button onclick={greet}>Greet</button>
Module Script
A<script module> tag runs once when the module first evaluates, rather than for each component instance:
The Template
The template section contains your HTML markup with Svelte’s template syntax:{expression}) are evaluated and inserted into the DOM.
The Style Block
CSS inside a<style> block is scoped to that component:
Component Instance
When a component is instantiated, Svelte:- Runs the
<script>block to initialize state and reactive declarations - Creates the DOM elements from your template
- Applies scoped styles
- Runs lifecycle hooks like
onMount - Sets up reactive dependencies for automatic updates
Best Practices
- Keep components focused on a single responsibility
- Use props to pass data from parent to child
- Emit events or use callbacks to communicate from child to parent
- Extract reusable logic into separate modules
- Use TypeScript for better type safety