DocsSvelte
- Legacy APIs<svelte:component>
gacy mode, it won't — we must use <svelte:component>, which destroys and recreates the component instance when the value of itsMiscSvelte 5 migration guide`<svelte:component>` is no longer necessaryTo make it dynamic you had to use <svelte:component>.This is no longer true in Svelte 5:<script> import A from './A.svelte';MiscSvelte 5 migration guide`<svelte:component>` is no longer necessaryDot notation indicates a componentIn Svelte 4, <foo.bar> would create an element with a tag name of "foo.bar". In Svelte 5, foo.bar is treated as a component instead. This is particulaIntroduction.svelte filesComponents are the building blocks of Svelte applications. They are written into .svelte files, using a superset of HTML.All three sections — script,StylingScoped stylesSvelte components can include a <style> element containing CSS that belongs to the component. This CSS is scoped by default, meaning that styles willSpecial elements<svelte:options><svelte:options option={value} />The <svelte:options> element provides a place to specify per-component compiler options, which are detailed in the coRuntimeLifecycle hooksIn Svelte 5, the component lifecycle consists of only two parts: Its creation and its destruction. Everything in-between — when certain state is updatRuntimeImperative component APIEvery Svelte application starts by imperatively creating a root component. On the client this component is mounted to a specific element. On the serveMiscCustom elementsSvelte components can also be compiled to custom elements (aka web components) using the customElement: true compiler option. You should specify a tagLegacy APIs<svelte:self>The <svelte:self> element allows a component to include itself, recursively.It cannot appear at the top level of your markup; it must be inside an ifLegacy APIsImperative component APIIn Svelte 3 and 4, the API for interacting with a component is different than in Svelte 5. Note that this page does not apply to legacy mode componentIntroductionOverviewSvelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript..Runes$bindableOrdinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app.In Svelte, component props can beTemplate syntaxawaitAs of Svelte 5.36, you can use the await keyword inside your components in three places where it was previously unavailable:at the top level of your cSpecial elements<svelte:window><svelte:window onevent={handler} /><svelte:window bind:prop={value} />The <svelte:window> element allows you to add event listeners to the window objeMiscTypeScriptYou can use TypeScript within Svelte components. IDE extensions like the Svelte VS Code extension will help you catch errors right in your editor, andLegacy APIs<slot>In Svelte 5, content can be passed to components in the form of snippets and rendered using render tags.In legacy mode, content inside component tagsStylingCustom propertiesYou can pass CSS custom properties — both static and dynamic — to components:<Slider bind:value min={0} max={100} --track-color="black" --thumb-cRuntimeStoresA store is an object that allows reactive access to a value via a simple store contract. The `svelte/store` module contains minimal store implementatiReferenceCompiler errorsn}`svelte_component_missing_this `<svelte:component>` must have a 'this' attributesvelte_element_missing_this `<svelte:element>Runes$propsThe inputs to a component are referred to as props, which is short for properties. You pass props to components just like you pass attributes to elemeRunes$hostWhen compiling a component as a custom element, the $host rune provides access to the host element, allowing you to (for example) dispatch custom evenRuntimeContextContext allows components to access values owned by parent components without passing them down as props (potentially through many layers of intermediMiscCustom elementsComponent lifecycleCustom elements are created from Svelte components using a wrapper approach. This means the inner Svelte component has no knowledge that it is a custoMiscCustom elementsComponent optionsWhen constructing a custom element, you can tailor several aspects by defining customElement as an object within <svelte:options> since Svelte 4. ThisMiscSvelte 5 migration guideComponents are no longer classesIn Svelte 3 and 4, components are classes. In Svelte 5 they are functions and should be instantiated differently. If you need to manually instantiateReferencesvelteComponentConstructorOptionsIn Svelte 4, components are classes. In Svelte 5, they are functions. Use mount instead to instantiate components. See migration guide for more info.MiscTypeScript<script lang="ts">To use TypeScript inside your Svelte components, add lang="ts" to your script tags:<script lang="ts"> let name: string = 'world'; function greet(naMiscTypeScriptThe `Component` typeSvelte components are of type Component. You can use it and its related types to express a variety of constraints.Using it together with dynamic compoMiscCustom elementsCaveats and limitationsCustom elements can be a useful way to package components for consumption in a non-Svelte app, as they will work with vanilla HTML and JavaScript as wMiscFrequently asked questionsCan I tell Svelte not to remove my unused styles?No. Svelte removes the styles from the component and warns you about them in order to prevent issues that would otherwise arise.Svelte's component styReferencesvelteSvelteComponentThis was the base class for Svelte components in Svelte 4. Svelte 5+ components are completely different under the hood. For typing, use Component insReferencesvelteSvelteComponentTypedUse Component instead. See migration guide for more information. class SvelteComponentTyped< Props extends Record<string, any> = Record<string, any>Runes$propsUpdating propsReferences to a prop inside a component update when the prop itself updates — when count changes in App.svelte, it will also change inside Child.sveltTemplate syntaxBasic markupCommentsYou can use HTML comments inside components.<!-- this is a comment! --><h1>Hello world</h1>Comments beginning with svelte-ignore disable warnings forTemplate syntaxbind:bind:property for componentsbind:property={variable}You can bind to component props using the same syntax as for elements.<Keypad bind:value={pin} />While Svelte props are reactiRuntimeImperative component APImountInstantiates a component and mounts it to the given target: import { mount } from 'svelte'; import App from './App.svelte'; const app = mount(App, {MiscTestingUnit and component tests with VitestUnit tests allow you to test small isolated parts of your code. Integration tests allow you to test parts of your application to see if they work togeMiscFrequently asked questionsHow do I document my components?In editors which use the Svelte Language Server you can document Components, functions and exports using specially formatted comments.<script> /** WhLegacy APIson:Component eventsComponents can dispatch events by creating a dispatcher when they are initialised:<!--- file: Stepper.svelte --> <script> import { createEventDispatcLegacy APIsImperative component APICreating a componentconst component = new Component(options);A client-side component — that is, a component compiled with generate: 'dom' (or the generate option left unsRuntimeStoresWhen to use storesPrior to Svelte 5, stores were the go-to solution for creating cross-component reactive states or extracting logic. With runes, these use cases have gRuntimeLifecycle hooksDeprecated: `beforeUpdate` / `afterUpdate`Svelte 4 contained hooks that ran before and after the component as a whole was updated. For backwards compatibility, these hooks were shimmed in SvelMiscSvelte 5 migration guideSnippets instead of slotsIn Svelte 4, content can be passed to components using slots. Svelte 5 replaces them with snippets, which are more powerful and flexible, and so slotsMiscFrequently asked questionsHow do I test Svelte apps?How your application is structured and where logic is defined will determine the best way to ensure it is properly tested. It is important to note thaReferencesvelte/compilerCompileOptionsinterface CompileOptions extends ModuleCompileOptions {/*…*/} name?: string; Sets the name of the resulting JavaScript class (though the compiler willTemplate syntax{#snippet ...}Snippet scopeSnippets can be declared anywhere inside your component. They can reference values declared outside themselves, for example in the <script> tag or inRuntimeContextsetContext` and getContext`As an alternative to createContext, you can use setContext and getContext directly. The parent component sets context with setContext(key, value)...<!MiscTestingComponent tests with StorybookStorybook is a tool for developing and documenting UI components, and it can also be used to test your components. They're run with Vitest's browser mReferencesvelteComponentPropsConvenience type to get the props the given component expects.Example: Ensure a variable contains the props expected by MyComponent:import type { CompMiscFrequently asked questionsHow do I write a mobile app with Svelte?While most mobile apps are written without using JavaScript, if you'd like to leverage your existing Svelte components and knowledge of Svelte when buReferencesvelte/compilerprintprint converts a Svelte AST node back into Svelte source code. It is primarily intended for tools that parse and transform components using the compilReferencesvelteComponentTypeThis type is obsolete when working with the new Component type. type ComponentType< Comp extends SvelteComponent = SvelteComponent > = (new ( optioReferencesvelte/compilerparseThe parse function parses a component, returning only its abstract syntax tree.The modern option (false by default in Svelte 5) makes the parser returReferencesvelte/legacyasClassComponentUse this only as a temporary solution to migrate your imperative component code to Svelte 5. Takes the component function and returns a Svelte 4 compaMiscSvelte 5 migration guideEvent changesComponent eventsIn Svelte 4, components could emit events by creating a dispatcher with createEventDispatcher.This function is deprecated in Svelte 5. Instead, componMiscSvelte 5 migration guideReactivity syntax changeslet → $stateIn Svelte 4, a let declaration at the top level of a component was implicitly reactive. In Svelte 5, things are more explicit: a variable is reactiveMiscSvelte 5 migration guideReactivity syntax changes$: → $derived/$effectIn Svelte 4, a $: statement at the top level of a component could be used to declare a derivation, i.e. state that is entirely defined through a compuMiscSvelte 5 migration guideReactivity syntax changesexport let → $propsIn Svelte 4, properties of a component were declared using export let. Each property was one declaration. In Svelte 5, all properties are declared thrReferencesvelteComponentExample:You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you wanMiscSvelte 5 migration guideComponents are no longer classesComponent typing changesThe change from classes towards functions is also reflected in the typings: SvelteComponent, the base class from Svelte 4, is deprecated in favour ofMiscSvelte 5 migration guideSnippets instead of slotsPassing data back upIn Svelte 4, you would pass data to a <slot /> and then retrieve it with let: in the parent component. In Svelte 5, snippets take on that responsibiliMiscSvelte 5 migration guideBreaking changes in runes mode`accessors` option is ignoredSetting the accessors option to true makes properties of a component directly accessible on the component instance.<svelte:options accessors={true} />Template syntax{#snippet ...}Passing snippets to componentsExplicit propsWithin the template, snippets are values just like any other. As such, they can be passed to components as props: <!--- file: App.svelte ---> <script>Template syntax{#snippet ...}Passing snippets to componentsImplicit propsAs an authoring convenience, snippets declared directly inside a component implicitly become props on the component: <!--- file: App.svelte ---> <scriMiscSvelte 5 migration guideComponents are no longer classesServer API changesSimilarly, components no longer have a render method when compiled for server-side rendering. Instead, pass the function to render from svelte/server:MiscSvelte 5 migration guideBreaking changes in runes modeAttribute/prop syntax is stricterIn Svelte 4, complex attribute values needn't be quoted: <Component prop=this{is}valid />This is a footgun. In runes mode, if you want to concatenateTemplate syntax{#snippet ...}Passing snippets to componentsImplicit `children` snippetAny content inside the component tags that is not a snippet declaration implicitly becomes part of the children snippet: <!--- file: App.svelte ---> <RuntimeStoressvelte/storewritableFunction that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional set and updateDocsSvelteKit
- Core conceptsPage options
By default, SvelteKit will render (or prerender) any component first on the server and send it to the client as HTML. It will then render the componenAdvancedPackagingYou can use SvelteKit to build apps as well as component libraries, using the @sveltejs/package package (npx sv create has an option to set this up foCore conceptsLoading dataBefore a `+page.svelte` component (and its containing `+layout.svelte` components) can be rendered, we often need to get some data. This is done by deAdvancedLink optionsIn SvelteKit, <a> elements (rather than framework-specific <Link> components) are used to navigate between the routes of your app. If the user clicksAdvancedShallow routingAs you navigate around a SvelteKit app, you create history entries. Clicking the back and forward buttons traverses through this list of entries, re-rCore conceptsState managementComponent and page state is preservedWhen you navigate around your application, SvelteKit reuses existing layout and page components. For example, if you have a route like this...<!--- fiGetting startedIntroductionSvelteKit vs SvelteSvelte renders UI components. You can compose these components and render an entire page with just Svelte, but you need more than just Svelte to writeCore conceptsLoading datapage.dataThe +page.svelte component, and each +layout.svelte component above it, has access to its own data plus all the data from its parents.In some cases, wAppendixGlossaryHydrationSvelte components store some state and update the DOM when the state is updated. When fetching data during SSR, by default SvelteKit will store this dAdvancedErrorsRendering errorsOrdinarily, if an error happens during server-side rendering (for example inside a component's <script> block or template), SvelteKit will return a 50Getting startedIntroductionWhat is Svelte?In short, Svelte is a way of writing user interface components — like a navigation bar, comment section, or contact form — that users see and interactCore conceptsState managementUsing state and stores with contextYou might wonder how we're able to use page.data and other app state (or app stores) if we can't use global state. The answer is that app state and apCore conceptsRouting+layoutSo far, we've treated pages as entirely standalone components — upon navigation, the existing +page.svelte component will be destroyed, and a new oneCore conceptsRouting+page+page.svelteA +page.svelte component defines a page of your app. By default, pages are rendered both on the server (SSR) for the initial request and in the browseBest practicesImages@sveltejs/enhanced-imgBasic usageUse in your .svelte components by using <enhanced:img> rather than <img> and referencing the image file with a Vite asset import path:<enhanced:img srGetting startedProject structureProject filessrcThe src directory contains the meat of your project. Everything except src/routes and src/app.html is optional.`lib` contains your library code (utiliCore conceptsRouting+layout+layout.jsJust like +page.svelte loading data from +page.js, your +layout.svelte component can get data from a `load` function in +layout.js. /** @type {importAdvancedPackagingAnatomy of a package.jsonsvelteThis is a legacy field that enabled tooling to recognise Svelte component libraries. It's no longer necessary when using the svelte export condition,Core conceptsRouting+layout+layout.svelteTo create a layout that applies to every page, make a file called src/routes/+layout.svelte. The default layout (the one that SvelteKit uses if you doAppendixMigrating from SapperPages and layoutsRenamed filesRoutes now are made up of the folder name exclusively to remove ambiguity, the folder names leading up to a +page.svelte correspond to the route. SeeTutorialBasic Svelte
- IntroductionYour first component
In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSSBindingsText inputsAs a general rule, data flow in Svelte is top down — a parent component can set props on a child component, and a component can set attributes on an eIntroductionWelcome to SvelteWhat is Svelte?Svelte is a tool for building web applications. Like other user interface frameworks, it allows you to build your app declaratively out of componentsTutorialBasic SvelteKit
- IntroductionWhat is SvelteKit?
Whereas Svelte is a component framework, SvelteKit is an app framework (or 'metaframework', depending on who you ask) that solves the tricky problemsRoutingLayoutsDifferent routes of your app will often share common UI. Instead of repeating it in each +page.svelte component, we can use a +layout.svelte componentShared modulesThe $lib aliasBecause SvelteKit uses directory-based routing, it's easy to place modules and components alongside the routes that use them. A good rule of thumb isTutorialAdvanced Svelte
- Advanced reactivityStores
Prior to the introduction of runes in Svelte 5, stores were the idiomatic way to handle reactive state outside components. That's no longer the case,Context APIsetContext and getContextThe context API provides a mechanism for components to 'talk' to each other without passing around data and functions as props, or dispatching lots ofDocsCLI
- APIsv-utilsTransformstransforms.svelte
Transform a Svelte component. The callback receives { ast, content, svelte, js }. import { transforms } from '@sveltejs/sv-utils'; sv.file( layoutPAPIsv-utilsTransformstransforms.svelteScriptTransform a Svelte component with a <script> block guaranteed. Pass { language } as the first argument. The callback receives { ast, content, svelte,