## docs/svelte/index.md
--- title: Svelte ---
## docs/svelte/01-introduction/index.md
--- title: Introduction ---
## docs/svelte/01-introduction/01-overview.md
--- title: Overview --- Svelte is a framework for building user interfaces on the web. It uses a compiler to turn declarative components written in HTML, CSS and JavaScript... ```svelte ``` ...into lean, tightly optimized JavaScript. You can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between. These pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions. You can also try Svelte online in the [playground](/playground) or, if you need a more fully-featured environment, on [StackBlitz](https://sveltekit.new).
## docs/svelte/01-introduction/02-getting-started.md
--- title: Getting started --- We recommend using [SvelteKit](../kit), which lets you [build almost anything](../kit/project-types). It's the official application framework from the Svelte team and powered by [Vite](https://vite.dev/). Create a new project with: ```bash npx sv create myapp cd myapp npm install npm run dev ``` Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later. ## Alternatives to SvelteKit You can also use Svelte directly with Vite by running `npm create vite@latest` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS, and CSS files inside the `dist` directory using [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte). In most cases, you will probably need to [choose a routing library](faq#Is-there-a-router) as well. >[!NOTE] Vite is often used in standalone mode to build [single page apps (SPAs)](../kit/glossary#SPA), which you can also [build with SvelteKit](../kit/single-page-apps). There are also plugins for [Rollup](https://github.com/sveltejs/rollup-plugin-svelte), [Webpack](https://github.com/sveltejs/svelte-loader) [and a few others](https://sveltesociety.dev/packages?category=build-plugins), but we recommend Vite. ## Editor tooling The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), and there are integrations with various other [editors](https://sveltesociety.dev/resources#editor-support) and tools as well. You can also check your code from the command line using [sv check](https://github.com/sveltejs/cli). ## Getting help Don't be shy about asking for help in the [Discord chatroom](/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte).
## docs/svelte/01-introduction/03-svelte-files.md
--- title: .svelte files --- Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. All three sections — script, styles and markup — are optional. ```svelte /// file: MyComponent.svelte ``` ## ` ``` You can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself. > In Svelte 4, this script tag was created using ` ``` Unlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable. ### Deep state If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates. State is proxified recursively until Svelte finds something other than an array or simple object. In a case like this... ```js let todos = $state([ { done: false, text: 'add more todos' } ]); ``` ...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property: ```js let todos = [{ done: false, text: 'add more todos' }]; //cut todos[0].done = !todos[0].done; ``` If you push a new object to the array, it will also be proxified: ```js let todos = [{ done: false, text: 'add more todos' }]; //cut todos.push({ done: false, text: 'eat lunch' }); ``` Note that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring: ```js let todos = [{ done: false, text: 'add more todos' }]; //cut let { done, text } = todos[0]; // this will not affect the value of `done` todos[0].done = !todos[0].done; ``` ### Classes You can also use `$state` in class fields (whether public or private): ```js // @errors: 7006 2554 class Todo { done = $state(false); text = $state(); constructor(text) { this.text = text; } reset() { this.text = ''; this.done = false; } } ``` When calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the `
` will result in `
hello
world
` (the `
` autoclosed the `
` because `
` cannot contain block-level elements) - `` will result in `` (the `
` is removed) - `
cell
` will result in `
cell
` (a `` is auto-inserted) This code will work when the component is rendered on the client (which is why this is a warning rather than an error), but if you use server rendering it will cause hydration to fail. ### non_reactive_update ``` `%name%` is updated, but is not declared with `$state(...)`. Changing its value will not correctly trigger updates ``` This warning is thrown when the compiler detects the following: - a variable was declared without `$state` or `$state.raw` - the variable is reassigned - the variable is read in a reactive context In this case, changing the value will not correctly trigger updates. Example: ```svelte
This value updates: {reactive}
This value does not update: {stale}
{ stale = 'updated'; reactive = 'updated'; }}>update ``` To fix this, wrap your variable declaration with `$state`. ### options_deprecated_accessors ``` The `accessors` option has been deprecated. It will have no effect in runes mode ``` ### options_deprecated_immutable ``` The `immutable` option has been deprecated. It will have no effect in runes mode ``` ### options_missing_custom_element ``` The `customElement` option is used when generating a custom element. Did you forget the `customElement: true` compile option? ``` ### options_removed_enable_sourcemap ``` The `enableSourcemap` option has been removed. Source maps are always generated now, and tooling can choose to ignore them ``` ### options_removed_hydratable ``` The `hydratable` option has been removed. Svelte components are always hydratable now ``` ### options_removed_loop_guard_timeout ``` The `loopGuardTimeout` option has been removed ``` ### options_renamed_ssr_dom ``` `generate: "dom"` and `generate: "ssr"` options have been renamed to "client" and "server" respectively ``` ### perf_avoid_inline_class ``` Avoid 'new class' — instead, declare the class at the top level scope ``` ### perf_avoid_nested_class ``` Avoid declaring classes below the top level scope ``` ### reactive_declaration_invalid_placement ``` Reactive declarations only exist at the top level of the instance script ``` ### reactive_declaration_module_script_dependency ``` Reassignments of module-level declarations will not cause reactive statements to update ``` ### script_context_deprecated ``` `context="module"` is deprecated, use the `module` attribute instead ``` ```svelte let foo = 'bar'; ``` ### script_unknown_attribute ``` Unrecognized attribute — should be one of `generics`, `lang` or `module`. If this exists for a preprocessor, ensure that the preprocessor removes it ``` ### slot_element_deprecated ``` Using `` to render parent content is deprecated. Use `{@render ...}` tags instead ``` See [the migration guide](v5-migration-guide#Snippets-instead-of-slots) for more info. ### state_referenced_locally ``` This reference only captures the initial value of `%name%`. Did you mean to reference it inside a %type% instead? ``` This warning is thrown when the compiler detects the following: - A reactive variable is declared - ...and later reassigned... - ...and referenced in the same scope This 'breaks the link' to the original state declaration. For example, if you pass the state to a function, the function loses access to the state once it is reassigned: ```svelte count++}> increment ``` ```svelte
The count is {count}
``` To fix this, reference the variable such that it is lazily evaluated. For the above example, this can be achieved by wrapping `count` in a function: ```svelte count++}> increment ``` ```svelte
The count is {count()}
``` For more info, see [Passing state into functions]($state#Passing-state-into-functions). ### store_rune_conflict ``` It looks like you're using the `$%name%` rune, but there is a local binding called `%name%`. Referencing a local variable with a `$` prefix will create a store subscription. Please rename `%name%` to avoid the ambiguity ``` ### svelte_component_deprecated ``` `` is deprecated in runes mode — components are dynamic by default ``` In previous versions of Svelte, the component constructor was fixed when the component was rendered. In other words, if you wanted `` to re-render when `X` changed, you would either have to use `` or put the component inside a `{#key X}...{/key}` block. In Svelte 5 this is no longer true — if `X` changes, `` re-renders. In some cases `` syntax can be used as a replacement; a lowercased variable with property access is recognized as a component in Svelte 5. For complex component resolution logic, an intermediary, capitalized variable may be necessary. E.g. in places where `@const` can be used: ```svelte {#each items as item} {@const Component = item.condition ? Y : Z} {/each} ``` A derived value may be used in other contexts: ```svelte ``` ### svelte_element_invalid_this ``` `this` should be an `{expression}`. Using a string attribute value will cause an error in future versions of Svelte ``` ### svelte_self_deprecated ``` `` is deprecated — use self-imports (e.g. `import %name% from './%basename%'`) instead ``` See [the note in the docs](legacy-svelte-self) for more info. ### unknown_code ``` `%code%` is not a recognised code ``` ``` `%code%` is not a recognised code (did you mean `%suggestion%`?) ```
## docs/svelte/98-reference/30-runtime-errors.md
--- title: 'Runtime errors' --- ## Client errors ### bind_invalid_checkbox_value ``` Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead ``` ### bind_invalid_export ``` Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`) ``` ### bind_not_bindable ``` A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()` ``` ### component_api_changed ``` Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5 ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### component_api_invalid_new ``` Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working. ``` See the [migration guide](/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information. ### derived_references_self ``` A derived value cannot reference itself recursively ``` ### each_key_duplicate ``` Keyed each block has duplicate key at indexes %a% and %b% ``` ``` Keyed each block has duplicate key `%value%` at indexes %a% and %b% ``` ### effect_in_teardown ``` `%rune%` cannot be used inside an effect cleanup function ``` ### effect_in_unowned_derived ``` Effect cannot be created inside a `$derived` value that was not itself created inside an effect ``` ### effect_orphan ``` `%rune%` can only be used inside an effect (e.g. during component initialisation) ``` ### effect_update_depth_exceeded ``` Maximum update depth exceeded. This can happen when a reactive block or effect repeatedly sets a new value. Svelte limits the number of nested updates to prevent infinite loops ``` ### hydration_failed ``` Failed to hydrate the application ``` ### invalid_snippet ``` Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}` ``` ### lifecycle_legacy_only ``` `%name%(...)` cannot be used in runes mode ``` ### props_invalid_value ``` Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value ``` ### props_rest_readonly ``` Rest element properties of `$props()` such as `%property%` are readonly ``` ### rune_outside_svelte ``` The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files ``` ### state_descriptors_fixed ``` Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`. ``` ### state_prototype_fixed ``` Cannot set prototype of `$state` object ``` ### state_unsafe_mutation ``` Updating state inside a derived or a template expression is forbidden. If the value should not be reactive, declare it without `$state` ``` This error occurs when state is updated while evaluating a `$derived`. You might encounter it while trying to 'derive' two pieces of state in one go: ```svelte count++}>{count}
{count} is even: {even}
{count} is odd: {odd}
``` This is forbidden because it introduces instability: if `
{count} is even: {even}
` is updated before `odd` is recalculated, `even` will be stale. In most cases the solution is to make everything derived: ```js let count = 0; //cut let even = $derived(count % 2 === 0); let odd = $derived(!even); ``` If side-effects are unavoidable, use [`$effect`]($effect) instead. ## Server errors ### lifecycle_function_unavailable ``` `%name%(...)` is not available on the server ``` Certain methods such as `mount` cannot be invoked while running in a server context. Avoid calling them eagerly, i.e. not during render. ## Shared errors ### invalid_default_snippet ``` Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead ``` This error would be thrown in a setup like this: ```svelte {entry} ``` ```svelte
{#each items as item}
{@render children(item)}
{/each}
``` Here, `List.svelte` is using `{@render children(item)` which means it expects `Parent.svelte` to use snippets. Instead, `Parent.svelte` uses the deprecated `let:` directive. This combination of APIs is incompatible, hence the error. ### invalid_snippet_arguments ``` A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}` ``` ### lifecycle_outside_component ``` `%name%(...)` can only be used during component initialisation ``` Certain lifecycle methods can only be used during component initialisation. To fix this, make sure you're invoking the method inside the _top level of the instance script_ of your component. ```svelte click me ``` ### store_invalid_shape ``` `%name%` is not a store with a `subscribe` method ``` ### svelte_element_invalid_this_value ``` The `this` prop on `` must be a string, if defined ```
## docs/svelte/98-reference/30-runtime-warnings.md
--- title: 'Runtime warnings' --- ## Client warnings ### assignment_value_stale ``` Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour. ``` Given a case like this... ```svelte add
items: {JSON.stringify(object.items)}
``` ...the array being pushed to when the button is first clicked is the `[]` on the right-hand side of the assignment, but the resulting value of `object.array` is an empty state proxy. As a result, the pushed value will be discarded. You can fix this by separating it into two statements: ```js let object = { array: [0] }; //cut function add() { object.array ??= []; object.array.push(object.array.length); } ``` ### binding_property_non_reactive ``` `%binding%` is binding to a non-reactive property ``` ``` `%binding%` (%location%) is binding to a non-reactive property ``` ### console_log_state ``` Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead ``` When logging a [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), browser devtools will log the proxy itself rather than the value it represents. In the case of Svelte, the 'target' of a `$state` proxy might not resemble its current value, which can be confusing. The easiest way to log a value as it changes over time is to use the [`$inspect`](/docs/svelte/$inspect) rune. Alternatively, to log things on a one-off basis (for example, inside an event handler) you can use [`$state.snapshot`](/docs/svelte/$state#$state.snapshot) to take a snapshot of the current value. ### event_handler_invalid ``` %handler% should be a function. Did you mean to %suggestion%? ``` ### hydration_attribute_changed ``` The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value ``` Certain attributes like `src` on an `` element will not be repaired during hydration, i.e. the server value will be kept. That's because updating these attributes can cause the image to be refetched (or in the case of an `