ExamplesIntroduction
DocsSvelte
- MiscCustom elements
orld' } = $props(); </script> <h1>Hello {name}!</h1> <slot />You can leave out the tag name for any of your inner comRuntimeContextelte'; setContext('my-context', 'hello from Parent.svelte'); </script>...and the child retrieves it with getContext:<!--- file:RunesWhat are runes?ke functions:let message = $state('hello');They differ from normal JavaScript functions in important ways, however:You don't needRunes$effectn your template — this is how `<h1>hello {name}!</h1>` updates when `name` changes.An effect can return a teardown functionTemplate syntax{@debug ...}}; </script> {@debug user} <h1>Hello {user.firstname}!</h1>{@debug ...} accepts a comma-separated list of variableRunes$statete`](https://svelte.dev/playground/hello-world?version=latest#H4sIAAAAAAAACpWR3WoDIRCFX2UqhWyIJL3erAulL9C7XnQLMe5ksbUqOpsfln33YuyGRunes$inspect$state(0); let message = $state('hello'); $inspect(count, message); // will console.log when `count` or `message` change </scrReferenceCompiler errorsyour components. Some examples:`<p>hello <div>world</div></p>` will result in `<p>hello </p><div>world</div><p></p>` (the `<Runes$bindablet.svelte'; let message = $state('hello'); </script> <FancyInput bind:value={message} /> <p>{message}</p>The parent component doReferenceCompiler warningser <p>:<!-- this HTML... --> <p><p>hello</p> <!-- results in this DOM structure --> <p></p> <p>hello</p>SLegacy APIs<svelte:fragment>ript> <Widget> <h1 slot="header">Hello</h1> <svelte:fragment slot="footer"> <p>All rights reserved.</p> <p>CSpecial elements<svelte:head>k or element.<svelte:head> <title>Hello world!</title> <meta name="description" content="This is where the descriptiTemplate syntaxBasic markupCommentsnts.<!-- this is a comment! --><h1>Hello world</h1>Comments beginning with svelte-ignore disable warnings for the nextMiscTypeScript<script lang="ts">ion greet(name: string) { alert(`Hello, ${name}!`); } </script> <button onclick={(e: Event) => greet(e.target.innerText)}> {nTemplate syntax{#snippet ...}Snippet scope} = $props(); </script> {#snippet hello(name)} <p>hello {name}! {message}!</p> {/snippet} {@render hello('alice')} {@rendTemplate syntax{@attach ...}Attachment factoriestippy.js'; let content = $state('Hello!'); /** * @param {string} content * @returns {import('svelte/attachments').AttachmeMiscSvelte 5 migration guideSnippets instead of slots> <hr /> <slot name="foo" message="hello" /><!--- file: Parent.svelte ---> <script> import Child from './Child.svelteTemplate syntaxBasic markupText expressionseed to wrap it in parentheses. <h1>Hello {name}!</h1> <p>{a} + {b} = {a + b}.</p> <div>{(/^[A-Za-z ]+$/).test(value) ? x :Referencesvelte/reactivitySvelteURLSearchParamsnew SvelteURLSearchParams('message=hello'); let key = $state('key'); let value = $state('value'); </script> <input bind:value=Legacy APIsexport letComponent exportsrt function greet(name) { alert(`hello ${name}!`); } </script><!--- file: App.svelte ---> <script> import Greeter from './GreeTemplate syntax{@attach ...}Passing attachments to componentsn.svelte'; let content = $state('Hello!'); /** * @param {string} content * @returns {import('svelte/attachments').AttachmeMiscFrequently asked questionsHow do I document my components?Arethra"> ``` --> <main> <h1> Hello, {name} </h1> </main>Note: The @component is necessary in the HTML comTemplate syntaxBasic markupComponent propsWidget foo={bar} answer={42} text="hello" />MiscTypeScriptTyping `$props`@render snippetWithStringArgument('hello')} </button>Special elements<svelte:boundary>Propertiespendingelte:boundary> <p>{await delayed('hello!')}</p> {#snippet pending()} <p>loading...</p> {/snippet} </svelte:boundaryMiscSvelte 5 migration guideComponents are no longer classesServer API changes= App.render({ props: { message: 'hello' }});--- +++const { html, head } = render(App, { props: { message: 'hello' }});+++In SvelMiscSvelte 5 migration guideOther breaking changes`oneventname` attributes no longer accept string valuess a string:<button onclick="alert('hello')">...</button>This is not recommended, and is no longer possible in Svelte 5, where pReferenceRuntime errorsClient errorseffect_update_depth_exceededto the array:let array = $state(['hello']); $effect(() => { array.push('goodbye'); });Note that it's fine for an effect to re-rDocsSvelteKit
- Core conceptsRouting
a user requests a page like `/blog/hello-world`[!NOTE] You can change `src/routes` to a different directory by editing the [projecAppendixMigrating to SvelteKit v2`resolvePath` has been removeda set of parameters (like { slug: 'hello' }) to a pathname. Unfortunately the return value didn't include the base path, limitingCore conceptsPage optionsentriesver links like <a href="/blog/hello-world"> which give it new pages to prerender.Most of the time, that's enough. InAppendixFrequently asked questionsHow do I use a client-side library accessing `document` or `window`?e-browser-only-library'); method('hello world'); });If the library you'd like to use is side-effect free you can also staticallyReference$app/pathsresolveme const resolved = resolve(`/blog/hello-world`); // using a route ID plus parameters const resolved = resolve('/blog/[slug]', {Core conceptsLoading dataUsing `getRequestEvent`n't get here return { message: `hello ${user.name}!` }; }Core conceptsRouting+page+page.svelte: src/routes/+page.svelte ---> <h1>Hello and welcome to my site!</h1> <a href="/about">About my site</a><!--- file: src/rCore conceptsRouting+page+page.jsparams }) { if (params.slug === 'hello-world') { return { title: 'Hello world!', content: 'Welcome to our blog. Lorem ipCore conceptsLoading dataUniversal vs serverWhen to use whichad() { return { serverMessage: 'hello from server load function' }; } /** @type {import('./$types').PageLoad} */ export asy