.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.
Variables declared at the top level can be referenced in the component’s markup. Use the
$state rune to create reactive state:<script>
import { onMount, tick } from 'svelte';
import Button from './Button.svelte';
import { formatDate } from './utils.js';
</script>
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