Lançado · em melhoria
Guia de SvelteKit · 3/6
Por enquanto, este capítulo está disponível apenas em inglês.
SvelteKit has two layers worth understanding: Svelte components and runes, which build the UI, and SvelteKit's routing and rendering model, which maps those components to URLs and renders them on the server and in the browser.
Each .svelte file is one component. Logic goes in <script>, markup follows it, and styles go in <style>, which is scoped to that component by default. Svelte compiles the file into code that updates exactly the parts of the DOM that changed, with no virtual DOM.
The current generation of Svelte (Svelte 5) expresses reactivity with runes, special symbols that start with $. They look like functions, but they are syntax understood by the compiler, so you never import them.
| Rune | Purpose |
|---|---|
$state | State that updates the UI when it changes |
$derived | A value computed from other state |
$effect | A side effect that runs after state changes (DOM work, timers, third-party libraries) |
$props | Receive the props passed by a parent |
$bindable | Mark a prop that a parent can bind to two-way |
<script lang="ts">
let items = $state<string[]>([]);
let text = $state('');
let total = $derived(items.length);
let empty = $derived(total === 0);
$effect(() => {
document.title = `${total} todos`;
});
function add() {
if (text.trim()) items.push(text.trim());
text = '';
}
</script>
<input bind:value={text} />
<button onclick={add}>Add</button>
{#if empty}
<p>Nothing to do.</p>
{:else}
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
{/if}Arrays and objects created with $state are deeply reactive, so mutating them directly with items.push() updates the UI. Reach for $derived whenever a value can be computed, and keep $effect for genuine side effects. Effects only run in the browser, never during server-side rendering.
A child component receives props through $props(). Instead of the older export let syntax and on:click directives, you destructure props and use plain attributes such as onclick. Markup passed to a child becomes a snippet, which the child renders with {@render ...}.
<!-- src/lib/components/Card.svelte -->
<script lang="ts">
import type { Snippet } from 'svelte';
let { title, highlighted = false, children }: {
title: string;
highlighted?: boolean;
children: Snippet;
} = $props();
</script>
<section class:highlighted>
<h2>{title}</h2>
{@render children()}
</section><script lang="ts">
import Card from '#lib/components/Card.svelte';
</script>
<Card title="Notice" highlighted>
<p>Scheduled maintenance tomorrow.</p>
</Card>In SvelteKit, the folder structure of src/routes is your URL structure. +page.svelte is a page, and +layout.svelte wraps the pages in its folder and below. A layout receives a children snippet and renders it where the page should appear.
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { page } from '$app/state';
let { children } = $props();
</script>
<nav>
<a href="/" aria-current={page.url.pathname === '/' ? 'page' : undefined}>Home</a>
<a href="/blog">Blog</a>
</nav>
<main>
{@render children()}
</main>page from $app/state is a reactive object holding the current URL, route params, page data and error. The older $app/stores module and its $page store have been removed in the current release. Links are ordinary <a> elements: SvelteKit intercepts clicks and performs a client-side navigation that updates only what changed.
By default, SvelteKit server-side renders the first request into complete HTML, hydrates it in the browser to make it interactive, and handles later navigations with client-side rendering. You change this per route with page options exported from +page.ts or +layout.ts.
// src/routes/about/+page.ts
export const prerender = true; // generate static HTML at build time
// in src/routes/dashboard/+layout.ts you might write
// export const ssr = false; // render in the browser only, SPA-style
// export const csr = false; // ship HTML with no JavaScript| Option | Default | Meaning |
|---|---|---|
prerender | false | true generates HTML at build time; 'auto' also keeps the route available for server rendering |
ssr | true | false sends an empty shell and renders in the browser |
csr | true | false ships no JavaScript |
Options set in the root layout apply to the whole app; options in a nested folder apply only below it. Prerender pages that are the same for everyone, like blog posts and docs; use SSR for per-user pages; and consider ssr = false for screens that lean heavily on browser APIs, such as an editor.
$state, $derived, $effect and $props.onclick; child markup is passed as snippets and drawn with {@render}.+page.svelte and +layout.svelte in src/routes define pages and shared shells.prerender, ssr and csr options.
0 comentários
Fazer login · Faça login para deixar um comentário.
Seja o primeiro a comentar.