Svelte is a compiler-based UI framework that transforms declarative component code into efficient imperative JavaScript that surgically updates the DOM
This guide will walk you through setting up Svelte and creating your first component.
npm install svelteCreate a file App.svelte:
<script>
let count = $state(0);
function increment() {
count++;
}
</script>
<button onclick={increment}>
Count: {count}
</button>Create main.js:
import { mount } from 'svelte';
import App from './App.svelte';
const app = mount(App, {
target: document.body
});Use a build tool like Vite, Rollup, or Webpack with Svelte plugin:
npm install -D @sveltejs/vite-plugin viteCreate vite.config.js:
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [svelte()]
});Use $state to create reactive variables:
<script>
let name = $state('World');
let count = $state(0);
</script>
<h1>Hello {name}!</h1>
<button onclick={() => count++}>
Clicked {count} times
</button>Use $derived to compute values from state:
<script>
let count = $state(0);
let doubled = $derived(count * 2);
</script>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>Use $effect to run side effects:
<script>
let count = $state(0);
$effect(() => {
console.log('Count changed:', count);
});
</script>Use onMount and onDestroy for component lifecycle:
<script>
import { onMount, onDestroy } from 'svelte';
onMount(() => {
console.log('Component mounted');
return () => {
console.log('Component will unmount');
};
});
onDestroy(() => {
console.log('Component destroyed');
});
</script>Define props using $props():
<script>
let { name = 'World', age } = $props();
</script>
<h1>Hello {name}!</h1>
{#if age}
<p>Age: {age}</p>
{/if}Create and use stores for shared state:
import { writable } from 'svelte/store';
export const count = writable(0);<script>
import { count } from './stores.js';
</script>
<button onclick={() => count.update(n => n + 1)}>
Count: {$count}
</button>Install with Tessl CLI
npx tessl i tessl/npm-svelte