To start with Svelte 5, run the following command in your terminal:
npm install svelte@next
To enable the new runes reactivity system, create or update your svelte.config.js
file:
module.exports = {
compilerOptions: {
runes: true
}
};
The $state
rune is used to create reactive state. It replaces the $:
syntax for simple state management.
$state counter = 0;
function increment() {
counter += 1;
}
The $derived
rune allows you to create derived state that depends on other state variables.
$state counter = 0;
$derived doubled = $state(() => counter * 2);
function increment() {
counter += 1;
}
The $effect
rune is used to perform side effects when certain values change.
$state counter = 0;
$effect(() => {
document.title = `Count: ${counter}`;
});
With Svelte 5, you can expose runes app-wide by creating .svelte.js
or .svelte.ts
files. This eliminates the need for prop-drilling and ad-hoc stores.
// global-runes.svelte.js
$state user = null;
$derived isLoggedIn = $state(() => user !== null);
<!-- App.svelte -->
<script>
import './global-runes.svelte.js';
</script>
{#if $isLoggedIn}
<div>Welcome, {$user.name}</div>
{/if}
Snippets allow you to create inline reusable chunks of code using the {@snippet}
directive.
<!-- Button.svelte -->
{@snippet Button --}
<button class="btn">
<slot></slot>
</button>
{/--}
<!-- Usage -->
{@render Button}Click me{/render}
Svelte 5 compiles your components into plain JavaScript functions, resulting in smaller bundle sizes and zero runtime overhead.
With runes, you no longer need to create separate stores for reactive state management. Everything is handled at the component level.
You can now write TypeScript directly in your Svelte components without any pre-processing.
<!-- Counter.svelte -->
<script lang="ts">
let count = 0;
function increment(): void {
count += 1;
}
</script>
<button on:click={increment}>
Count: {count}
</button>
Svelte 5 allows you to define components as functions for better tree-shaking and inlining.
<!-- Button.svelte -->
<script lang="ts">
export default function Button() {
return <button class="btn"><slot></slot></button>;
}
</script>
Svelte 5 introduces a new era of reactivity and component-first development. With runes, universal reactivity, snippets, and native TypeScript support, you can build faster, smaller, and more maintainable applications. Start exploring these features today!