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 isIntroduction.svelte filesComponents are the building blocks of Svelte applications. They are written into .svelte files, using a superset of HTML.All three sections — script,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$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 beRunes$hostWhen compiling a component as a custom element, the $host rune provides access to the host element, allowing you to (for example) dispatch custom evenTemplate syntax{@html ...}To inject raw HTML into your component, use the {@html ...} tag:<article> {@html content} </article>[!NOTE] Make sure that you either escape the passStylingScoped stylesSvelte components can include a <style> element containing CSS that belongs to the component. This CSS is scoped by default, meaning that styles willStylingCustom propertiesYou can pass CSS custom properties — both static and dynamic — to components:<Slider bind:value min={0} max={100} --track-color="black" --thumb-cRuntimeContextContext allows components to access values owned by parent components without passing them down as props (potentially through many layers of intermediRuntimeLifecycle 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 APIsexport letIn runes mode, component props are declared with the `$props` rune, allowing parent components to pass in data.In legacy mode, props are marked with tLegacy 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 tagsLegacy APIs$$slotsIn runes mode, we know which snippets were provided to a component, as they're just normal props.In legacy mode, the way to know if content was providLegacy 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 componentMiscCustom 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 instantiateReferencesvelteComponentCan be used to create strongly typed Svelte components.ReferencesvelteComponentConstructorOptionsIn Svelte 4, components are classes. In Svelte 5, they are functions. Use mount instead to instantiate components. See migration guide for more info.ReferencesvelteComponentEventsThe new Component type does not have a dedicated Events type. Use ComponentProps instead. type ComponentEvents<Comp extends SvelteComponent> = CompReferencesvelteComponentPropsConvenience type to get the props the given component expects.Example: Ensure a variable contains the props expected by MyComponent:import type { CompReferencesvelteComponentTypeThis type is obsolete when working with the new Component type. type ComponentType< Comp extends SvelteComponent = SvelteComponent > = (new ( optioLegacy APIsexport letComponent exportsAn exported const, class or function declaration is not considered a prop — instead, it becomes part of the component's API:<!--- file: Greeter.svelteLegacy APIson:Component eventsComponents can dispatch events by creating a dispatcher when they are initialised:<!--- file: Stepper.svelte --> <script> import { createEventDispatcLegacy APIsImperative component APIComponent propscomponent.prop; component.prop = value;If a component is compiled with accessors: true, each instance will have getters and setters corresponding toRunes$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.sveltRunes$propsType safetyYou can add type safety to your components by annotating your props, as you would with any other variable declaration. In TypeScript that might look lTemplate 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 reactiRuntimeContextReplacing global stateWhen you have state shared by many different components, you might be tempted to put it in its own module and just import it wherever it's needed: exRuntimeLifecycle hooksonMountThe onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initiaRuntimeImperative component APImountInstantiates a component and mounts it to the given target: import { mount } from 'svelte'; import App from './App.svelte'; const app = mount(App, {RuntimeImperative component APIunmountUnmounts a component that was previously created with `mount` or `hydrate`.If options.outro is true, transitions will play before the component is remMiscTypeScript<script lang="ts">To use TypeScript inside your Svelte components, add lang="ts" to your script tags:<script lang="ts"> let name: string = 'world'; functioMiscTypeScriptTyping wrapper componentsIn case you're writing a component that wraps a native element, you may want to expose all the attributes of the underlying element to the user. In thMiscTypeScriptThe `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 compoMiscSvelte 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 as such sMiscFrequently 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> /** WhMiscFrequently asked questionsIs there a UI component library?There are several UI component libraries as well as standalone components. Find them under the design systems section of the components page on the SvMiscFrequently 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 thaMiscFrequently 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>ReferencesveltehydrateHydrates a component on the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component functioReferencesveltemountMounts a component to the given target and returns the exports and potentially the props (if compiled with accessors: true) of the component. TransitiReferencesvelteunmountUnmounts a component that was previously mounted using mount or hydrate.Since 5.13.0, if options.outro is true, transitions will play before the compoReferencesvelte/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/compilerCompileOptionsinterface CompileOptions extends ModuleCompileOptions {/*…*/} name?: string; Sets the name of the resulting JavaScript class (though the compiler willReferencesvelte/legacyLegacyComponentTypeSupport using the component as both a class and function during the transition period type LegacyComponentType = { new (o: ComponentConstructorOptionLegacy APIs<slot>Named slotsA component can have named slots in addition to the default slot. On the parent side, add a slot="..." attribute to an element, component orLegacy 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 unsLegacy APIsImperative component API$setcomponent.$set(props);Programmatically sets props on an instance. component.$set({ x: 1 }) is equivalent to x = 1 inside the component's <script> blocLegacy APIsImperative component API$oncomponent.$on(ev, callback);Causes the callback function to be called whenever the component dispatches an event.A function is returned that will remoLegacy APIsImperative component API$destroycomponent.$destroy();Removes a component from the DOM and triggers any onDestroy handlers.[!NOTE] In Svelte 5+, use [`unmount`](svelte#unmount) insteaLegacy APIsImperative component APIServer-side component APIconst result = Component.render(...)Unlike client-side components, server-side components don't have a lifespan after you render them — their whole joMiscTestingUnit and integration testing using VitestComponent testingIt is possible to test your components in isolation using Vitest.[!NOTE] Before writing component tests, think about whether you actually need to testMiscSvelte 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 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 ofReferenceRuntime errorsClient errorscomponent_api_changedCalling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5See the migration guide for more information.ReferenceRuntime errorsClient errorscomponent_api_invalid_newAttempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `coTemplate 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 (demo):<!--- file: App.svelteRuntimeStoressvelte/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 updateMiscSvelte 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 thrMiscSvelte 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 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 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} />ReferencesvelteComponentExample:You have component library on npm called component-library, from which you export a component called MyComponent. For Svelte+TypeScript users, you wanReferenceRuntime errorsShared errorsinvalid_default_snippetCannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet insteadThis error would be thrownReferenceRuntime errorsShared errorslifecycle_outside_component`%name%(...)` can only be used during component initialisationCertain lifecycle methods can only be used during component initialisation. To fix this,DocsSvelteKit
- 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 componenAdvancedLink optionsIn SvelteKit, <a> elements (rather than framework-specific <Link> components) are used to navigate between the routes of your app. If the user clicksAdvancedPackagingYou 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 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 dCore 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 browseCore 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 {importBest 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 srAppendixMigrating 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
- EventsComponent events
You can pass event handlers to components like any other prop. In Stepper.svelte, add increment and decrement props... <script> let +++{ increment,Classes and stylesComponent stylesOften, you need to influence the styles inside a child component. Perhaps we want to make these boxes red, green and blue.One way to do this is with tIntroductionYour first componentIn Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSSIntroductionNested componentsIt would be impractical to put your entire app in a single component. Instead, we can import components from other files and include them in our markuReactivityUniversal reactivityIn the preceding exercises, we used runes to add reactivity inside components. But we can also use runes outside components, for example to share someBindingsText 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 eIntroductionYour first componentAdding dataA component that just renders some static markup isn't very interesting. Let's add some data.First, add a script tag to your component and declare a nTutorialAdvanced Svelte
- Advanced bindingsComponent bindings
Just as you can bind to properties of DOM elements, you can bind to component props. For example, we can bind to the value prop of this <Keypad> compoAdvanced reactivityStoresPrior 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,Advanced bindingsBinding to component instancesJust as you can bind to DOM elements, you can bind to component instances themselves with bind:this.This is useful in the rare cases that you need toContext 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 of<script module>Sharing codeIn all the examples we've seen so far, the <script> block contains code that runs when each component instance is initialised. For the vast majority oTutorialBasic 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 problemsShared 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 is