Svelte Overview
Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.
Key Features
- No Virtual DOM: Compiles to efficient JavaScript.
- Reactivity: Automatic updates when state changes.
- Scoped Styles: CSS automatically scoped to components.
- Stores: Simple state management solution.
- Accessibility: Built-in a11y warnings.
- Small Bundle Size: Less code shipped to browser.
- SvelteKit: Application framework for Svelte.
Common Use Cases
Performance-Critical Apps
Where bundle size and runtime efficiency matter.
Interactive Widgets
Embeddable components with minimal overhead.
Full-Stack Applications
Using SvelteKit for server-rendered apps.
Progressive Enhancement
Adding interactivity to traditional server-rendered pages.
Example Code
<!-- Svelte component example -->
<script>
let count = 0;
function increment() {
count += 1;
}
// Reactive declaration
$: doubled = count * 2;
</script>
<style>
button {
background-color: #ff3e00;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
}
</style>
<button on:click={increment}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>Double: {doubled}</p>
<!-- Store example -->
<script>
import { writable } from 'svelte/store';
const name = writable('guest');
function setName() {
$name = 'Alice';
}
</script>
<h1>Hello {$name}!</h1>
<button on:click={setName}>Set Name</button>
<!-- SvelteKit page example -->
<!--
<script context="module">
export async function load({ fetch }) {
const res = await fetch('/api/data');
const data = await res.json();
return {
props: { data }
};
}
</script>
<script>
export let data;
</script>
<h1>{data.title}</h1>
-->