============================================================
FILE: .agents/skills/performance-investigation/SKILL.md
============================================================
---
name: performance-investigation
description: Investigate performance regressions and find opportunities for optimization
---
## Quick start
1. Start from a branch you want to measure (for example `foo`).
2. Run:
```sh
pnpm bench:compare main foo
```
If you pass one branch, `bench:compare` automatically compares it to `main`.
## Where outputs go
- Summary report: `benchmarking/compare/.results/report.txt`
- Raw benchmark numbers:
- `benchmarking/compare/.results/main.json`
- `benchmarking/compare/.results/.json`
- CPU profiles (per benchmark, per branch):
- `benchmarking/compare/.profiles/main/*.cpuprofile`
- `benchmarking/compare/.profiles/main/*.md`
- `benchmarking/compare/.profiles//*.cpuprofile`
- `benchmarking/compare/.profiles//*.md`
The `.md` files are generated summaries of the CPU profile and are usually the fastest way to inspect hotspots.
## Suggested investigation flow
1. Open `benchmarking/compare/.results/report.txt` and identify largest regressions first.
2. For each high-delta benchmark, compare:
- `benchmarking/compare/.profiles/main/.md`
- `benchmarking/compare/.profiles//.md`
3. Look for changes in self/inclusive hotspot share in runtime internals (`runtime.js`, `reactivity/batch.js`, `reactivity/deriveds.js`, `reactivity/sources.js`).
4. Make one optimization change at a time, then re-run targeted benches before re-running full compare.
## Fast benchmark loops
Run only selected reactivity benchmarks by substring:
```sh
pnpm bench kairo_mux kairo_deep kairo_broad kairo_triangle
pnpm bench repeated_deps sbench_create_signals mol_owned
```
## Tests to run after perf changes
Runtime reactivity regressions are most likely in runes runtime tests:
```sh
pnpm test runtime-runes
```
## Helpful script
For quick cpuprofile hotspot deltas between two branches:
```sh
node benchmarking/compare/profile-diff.mjs kairo_mux_owned main foo
```
This prints top function sample-share deltas for the selected benchmark.
## Practical gotchas
- `bench:compare` checks out branches while running. Avoid uncommitted changes (or stash them) so branch switching is safe.
- Each `bench:compare` run rewrites `benchmarking/compare/.results` and `benchmarking/compare/.profiles`.
============================================================
FILE: .changeset/README.md
============================================================
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
============================================================
FILE: .github/ISSUE_TEMPLATE.md
============================================================
---
Before filing an issue we'd appreciate it if you could take a moment to ensure
there isn't already an open issue or pull-request.
---
If there's an existing issue, please add a :+1: reaction to the description of
the issue. One way we prioritize issues is by the number of :+1: reactions on
their descriptions. Please DO NOT add `+1` or :+1: comments.
### Feature requests and proposals
We're excited to hear how we can make Svelte better. Please add as much detail
as you can on your use case. To propose an implementation of a large feature or
change, please create an [RFC](https://github.com/sveltejs/rfcs).
### Bugs
If you're filing an issue about a bug please include as much information
as you can including the following.
- Your browser and the version: (e.x. Chrome 52.1, Firefox 48.0, IE 10)
- Your operating system: (e.x. OS X 10, Windows XP, etc)
- Svelte version (Please check you can reproduce the issue with the latest release!)
- Whether your project uses Webpack or Rollup
- _Repeatable steps to reproduce the issue_
## Thanks for being part of Svelte!
============================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
============================================================
### Before submitting the PR, please make sure you do the following
- [ ] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [ ] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`.
- [ ] This message body should clearly illustrate what problems it solves.
- [ ] Ideally, include a test that fails without this PR but passes with it.
- [ ] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`).
### Tests and linting
- [ ] Run the tests with `pnpm test` and lint the project with `pnpm lint`
============================================================
FILE: AGENTS.md
============================================================
# Svelte Coding Agent Guide
This guide is for AI coding agents working in the Svelte monorepo.
**Important:** Read and follow [`CONTRIBUTING.md`](./CONTRIBUTING.md) as well - it contains essential information about testing, code structure, and contribution guidelines that applies here.
## Quick Reference
If asked to do a performance investigation, use the `performance-investigation` skill.
============================================================
FILE: CODE_OF_CONDUCT.md
============================================================
This repository is governed by the Svelte Code of Conduct.
https://github.com/sveltejs/community/blob/main/CODE_OF_CONDUCT.md
============================================================
FILE: CONTRIBUTING.md
============================================================
# Contributing to Svelte
Svelte is a new way to build web applications. It's a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.
The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies. These resources help people who want to learn how to run and contribute to open source projects. Contributors and people new to open source alike will find the following guides especially useful:
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Building Welcoming Communities](https://opensource.guide/building-community/)
## Get involved
There are many ways to contribute to Svelte, and many of them do not involve writing any code. Here are a few ideas to get started:
- Simply start using Svelte. Go through the [Getting Started](https://svelte.dev/docs#getting-started) guide. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](#reporting-new-issues).
- Look through the [open issues](https://github.com/sveltejs/svelte/issues). A good starting point would be issues tagged [good first issue](https://github.com/sveltejs/svelte/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). Provide workarounds, ask for clarification, or suggest labels. Help [triage issues](#triaging-issues-and-pull-requests).
- If you find an issue you would like to fix, [open a pull request](#pull-requests).
- Read through our [tutorials](https://svelte.dev/tutorial). If you find anything that is confusing or can be improved, you can make edits by clicking "Edit this page" at the bottom left of the tutorial page.
- Take a look at the [features requested](https://github.com/sveltejs/svelte/labels/feature%20request) by others in the community and consider opening a pull request if you see something you want to work on.
Contributions are very welcome. If you think you need help planning your contribution, please ping us on Discord at [svelte.dev/chat](https://svelte.dev/chat) and let us know you are looking for a bit of help.
### Triaging issues and pull requests
One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.
- Ask for more information if you believe the issue does not provide all the details required to solve it.
- Flag issues that are stale or that should be closed.
- Ask for test plans and review code.
## Our process
### RFCs
If you'd like to propose an implementation for a large new feature or change then please [create an RFC](https://github.com/sveltejs/rfcs) to discuss it up front.
### Roadmap
When deciding where to contribute, you may wish to take a look at [our roadmap](https://svelte.dev/roadmap). The Svelte team generally works on a single major effort at a time. This has a couple benefits for us as maintainers. First, it allows us to focus and make noticeable progress in an area being proactive rather than reactive. Secondly, it allows us to handle related issues and PRs together. By batching issues and PRs together we’re able to ensure implementations and fixes holistically address the set of problems and use cases encountered by our users.
### Maintainer meetings
The maintainers meet on the final Saturday of each month. While these meetings are not open publicly, we will report back by leaving a comment on each issue discussed. We will generally discuss items aligning with our roadmap, but major PRs needing discussion amongst the maintainers can be added to the agenda for the monthly maintainer’s meeting. However, we typically are only able to get to a couple of items that are not aligned with our current priority.
### Prioritization
We do our best to review PRs and RFCs as they are sent, but it is difficult to keep up. We welcome help in reviewing PRs, RFCs, and issues. If an item aligns with the current priority on our [roadmap](https://svelte.dev/roadmap), it is more likely to be reviewed quickly. PRs to the most important and active ones repositories get reviewed more quickly while PRs to smaller inactive repos may sit for a bit before we periodically come by and review the pending PRs in a batch.
## Bugs
We use [GitHub issues](https://github.com/sveltejs/svelte/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new unreported bug, you can submit a [bug report](#reporting-new-issues).
If you have questions about using Svelte, contact us on Discord at [svelte.dev/chat](https://svelte.dev/chat), and we will do our best to answer your questions.
If you see anything you'd like to be implemented, create a [feature request issue](https://github.com/sveltejs/svelte/issues/new?template=feature_request.yml).
### Reporting new issues
When [opening a new issue](https://github.com/sveltejs/svelte/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not being managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
- **One issue, one bug:** Please report a single bug per issue.
- **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort. If possible, use the [REPL](https://svelte.dev/repl) to create your reproduction.
## Pull requests
### Proposing a change
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/sveltejs/svelte/issues/new?template=feature_request.yml).
If you're only fixing a bug, it's fine to submit a pull request right away, but we still recommend that you file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
Small pull requests are much easier to review and more likely to get merged.
### Installation
Ensure you have [pnpm](https://pnpm.io/installation) installed. After cloning the repository, run `pnpm install`.
### Developing
To build the UMD version of `svelte/compiler` (this is only necessary for CommonJS consumers, or in-browser use), run `pnpm build` inside `packages/svelte`. To rebuild whenever source files change, run `pnpm dev`.
### Creating a branch
Fork [the repository](https://github.com/sveltejs/svelte) and create your branch from `main`. If you've never sent a GitHub pull request before, you can learn how from [this free video series](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github).
### Testing
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI.
- If you've changed APIs, update the documentation.
#### Writing tests
All tests are located in the `/tests` folder.
Test samples are kept in `/tests/xxx/samples` folders.
#### Running tests
> PREREQUISITE: Install chromium via playwright by running `pnpm playwright install chromium`
1. To run test, run `pnpm test`.
1. To run a particular test suite, use `pnpm test `, for example:
```sh
pnpm test validator
```
1. To filter tests _within_ a test suite, use `pnpm test -t `, for example:
```sh
pnpm test validator -t a11y-alt-text
```
(You can also do `FILTER= pnpm test ` which removes other tests rather than simply skipping them — this will result in faster and more compact test results, but it's non-idiomatic. Choose your fighter.)
##### Updating `.expected` files
1. Tests suites like `snapshot` and `parser` assert that the generated output matches the existing snapshot.
1. To update these snapshots, run `UPDATE_SNAPSHOTS=true pnpm test`.
### Typechecking
To typecheck the codebase, run `pnpm check` inside `packages/svelte`. To typecheck in watch mode, run `pnpm check:watch`.
### Style guide
[Eslint](https://eslint.org) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `pnpm lint`.
#### Code conventions
- `snake_case` for internal variable names and methods.
- `camelCase` for public variable names and methods.
### Generating types
Types are auto-generated from the source, but the result is checked in to ensure no accidental changes slip through. Run `pnpm generate:types` to regenerate the types.
### Sending your pull request
Please make sure the following is done when submitting a pull request:
1. Describe your **test plan** in your pull request description. Make sure to test your changes.
1. Make sure your code lints (`pnpm lint`).
1. Make sure your tests pass (`pnpm test`).
All pull requests should be opened against the `main` branch. Make sure the PR does only one thing, otherwise please split it. If this change should contribute to a version bump, run `npx changeset` at the root of the repository after a code change and select the appropriate packages.
#### Breaking changes
When adding a new breaking change, follow this template in your pull request:
```md
### New breaking change here
- **Who does this affect**:
- **How to migrate**:
- **Why make this breaking change**:
- **Severity (number of people affected x effort)**:
```
### Reviewing pull requests
If you'd like to manually test a pull request in another pnpm project, you can do so by running `pnpm add -D "github:sveltejs/svelte#path:packages/svelte&branch-name"` in that project.
## License
By contributing to Svelte, you agree that your contributions will be licensed under its [MIT license](https://github.com/sveltejs/svelte/blob/master/LICENSE.md).
## Questions
Feel free to ask in [#contributing](https://discord.com/channels/457912077277855764/750401468569354431) on [Discord](https://svelte.dev/chat) if you have questions about our process, how to proceed, etc.
============================================================
FILE: LICENSE.md
============================================================
Copyright (c) 2016-2025 [Svelte Contributors](https://github.com/sveltejs/svelte/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
============================================================
FILE: README.md
============================================================
[](LICENSE.md) [](https://svelte.dev/chat)
## What is Svelte?
Svelte is a new way to build web applications. It's a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.
Learn more at the [Svelte website](https://svelte.dev), or stop by the [Discord chatroom](https://svelte.dev/chat).
## Supporting Svelte
Svelte is an MIT-licensed open source project with its ongoing development made possible entirely by fantastic volunteers. If you'd like to support their efforts, please consider:
- [Becoming a backer on Open Collective](https://opencollective.com/svelte).
Funds donated via Open Collective will be used for compensating expenses related to Svelte's development such as hosting costs. If sufficient donations are received, funds may also be used to support Svelte's development more directly.
## Roadmap
You may view [our roadmap](https://svelte.dev/roadmap) if you'd like to see what we're currently working on.
## Contributing
Please see the [Contributing Guide](CONTRIBUTING.md) and the [`svelte`](packages/svelte) package for information on contributing to Svelte.
## Is svelte.dev down?
Probably not, but it's possible. If you can't seem to access any `.dev` sites, check out [this SuperUser question and answer](https://superuser.com/q/1413402).
## License
[MIT](LICENSE.md)
============================================================
FILE: documentation/docs/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).
============================================================
FILE: documentation/docs/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:
```sh
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 via [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte) by running `npm create vite@latest` and selecting the `svelte` option (or, if working with an existing project, adding the plugin to your `vite.config.js` file). With this, `npm run build` will generate HTML, JS, and CSS files inside the `dist` directory. In most cases, you will probably need to [choose a routing library](/packages#routing) 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 other bundlers](/packages#bundler-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/collection/editor-support-c85c080efc292a34) and tools as well.
You can also check your code from the command line using [`npx sv check`](https://svelte.dev/docs/cli/sv-check).
## 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).
============================================================
FILE: documentation/docs/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.
> [!NOTE] If you are using TypeScript and import such exports from a `module` block into a `.ts` file, make sure to have your editor setup so that TypeScript knows about them. This is the case for our VS Code extension and the IntelliJ plugin, but in other cases you might need to setup our [TypeScript editor plugin](https://www.npmjs.com/package/typescript-svelte-plugin).
> [!LEGACY]
> 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 (like a class or an object created with `Object.create`). 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] When you update properties of proxies, the original object is _not_ mutated. If you need to use your own proxy handlers in a state proxy, [you should wrap the object _after_ wrapping it in `$state`](https://svelte.dev/playground/hello-world?version=latest#H4sIAAAAAAAACpWR3WoDIRCFX2UqhWyIJL3erAulL9C7XnQLMe5ksbUqOpsfln33YuyGFNJC8UKdc2bOhw7Myk9kJXsJ0nttO9jcR5KEG9AWJDwHdzwxznbaYGTl68Do5JM_FRifuh-9X8Y9Gkq1rYx4q66cJbQUWcmqqIL2VDe2IYMEbvuOikBADi-GJDSkXG-phId0G-frye2DO2psQYDFQ0Ys8gQO350dUkEydEg82T0GOs0nsSG9g2IqgxACZueo2ZUlpdvoDC6N64qsg1QKY8T2bpZp8gpIfbCQ85Zn50Ud82HkeY83uDjspenxv3jXcSDyjPWf9L1vJf0GH666J-jLu1ery4dV257IWXBWGa0-xFDMQdTTn2ScxWKsn86ROsLwQxqrVR5QM84Ij8TKFD2-cUZSm4O2LSt30kQcvwCgCmfZnAIAAA==).
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
Class instances are not proxied. Instead, you can use `$state` in class fields (whether public or private), or as the first assignment to a property immediately inside the `constructor`:
```js
// @errors: 7006 2554
class Todo {
done = $state(false);
constructor(text) {
this.text = $state(text);
}
reset() {
this.text = '';
this.done = false;
}
}
```
> [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields. This means the properties are not enumerable.
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
```
### 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%`?)
```
============================================================
FILE: documentation/docs/98-reference/.generated/server-errors.md
============================================================
### async_local_storage_unavailable
```
The node API `AsyncLocalStorage` is not available, but is required to use async server rendering.
```
Some platforms require configuration flags to enable this API. Consult your platform's documentation.
### await_invalid
```
Encountered asynchronous work while rendering synchronously.
```
You (or the framework you're using) called [`render(...)`](svelte-server#render) with a component containing an `await` expression. Either `await` the result of `render` or wrap the `await` (or the component containing it) in a [``](svelte-boundary) with a `pending` snippet.
### dynamic_element_invalid_tag
```
`` is not a valid element name — the element will not be rendered
```
The value passed to the `this` prop of `` must be a valid HTML element, SVG element, MathML element, or custom element name. A value containing invalid characters (such as whitespace or special characters) was provided, which could be a security risk. Ensure only valid tag names are passed.
### html_deprecated
```
The `html` property of server render results has been deprecated. Use `body` instead.
```
### hydratable_clobbering
```
Attempted to set `hydratable` with key `%key%` twice with different values.
%stack%
```
This error occurs when using `hydratable` multiple times with the same key. To avoid this, you can:
- Ensure all invocations with the same key result in the same value
- Update the keys to make both instances unique
```svelte
```
### hydratable_serialization_failed
```
Failed to serialize `hydratable` data for key `%key%`.
`hydratable` can serialize anything [`uneval` from `devalue`](https://npmjs.com/package/uneval) can, plus Promises.
Cause:
%stack%
```
### invalid_csp
```
`csp.nonce` was set while `csp.hash` was `true`. These options cannot be used simultaneously.
```
### invalid_id_prefix
```
The `idPrefix` option cannot include `--`.
```
### 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.
### server_context_required
```
Could not resolve `render` context.
```
Certain functions such as `hydratable` cannot be invoked outside of a `render(...)` call, such as at the top level of a module.
============================================================
FILE: documentation/docs/98-reference/.generated/server-warnings.md
============================================================
### unresolved_hydratable
```
A `hydratable` value with key `%key%` was created, but at least part of it was not used during the render.
The `hydratable` was initialized in:
%stack%
```
The most likely cause of this is creating a `hydratable` in the `script` block of your component and then `await`ing
the result inside a `svelte:boundary` with a `pending` snippet:
```svelte
{(await user).name}
{#snippet pending()}
Loading...
{/snippet}
```
Consider inlining the `hydratable` call inside the boundary so that it's not called on the server.
Note that this can also happen when a `hydratable` contains multiple promises and some but not all of them have been used.
============================================================
FILE: documentation/docs/98-reference/.generated/shared-errors.md
============================================================
### experimental_async_required
```
Cannot use `%name%(...)` unless the `experimental.async` compiler option is `true`
```
### 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 ...}`
```
### invariant_violation
```
An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: "%message%"
```
### 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
```
### missing_context
```
Context was not set in a parent component
```
The [`createContext()`](svelte#createContext) utility returns a `[get, set]` pair of functions. `get` will throw an error if `set` was not used to set the context in a parent component.
### snippet_without_render_tag
```
Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.
```
A component throwing this error will look something like this (`children` is not being rendered):
```svelte
{children}
```
...or like this (a parent component is passing a snippet where a non-snippet value is expected):
```svelte
{#snippet label()}
Hi!
{/snippet}
```
```svelte
{label}
```
### 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
```
============================================================
FILE: documentation/docs/98-reference/.generated/shared-warnings.md
============================================================
### dynamic_void_element_content
```
`` is a void element — it cannot have content
```
Elements such as `` cannot have content, any children passed to these elements will be ignored.
### state_snapshot_uncloneable
```
Value cannot be cloned with `$state.snapshot` — the original value was returned
```
```
The following properties cannot be cloned with `$state.snapshot` — the return value contains the originals:
%properties%
```
`$state.snapshot` tries to clone the given value in order to return a reference that no longer changes. Certain objects may not be cloneable, in which case the original value is returned. In the following example, `property` is cloned, but `window` is not, because DOM elements are uncloneable:
```js
const object = $state({ property: 'this is cloneable', window })
const snapshot = $state.snapshot(object);
```
============================================================
FILE: documentation/docs/98-reference/20-svelte.md
============================================================
---
title: svelte
---
> MODULE: svelte
============================================================
FILE: documentation/docs/98-reference/21-svelte-action.md
============================================================
---
title: svelte/action
---
This module provides types for [actions](use), which have been superseded by [attachments](@attach).
> MODULE: svelte/action
============================================================
FILE: documentation/docs/98-reference/21-svelte-animate.md
============================================================
---
title: svelte/animate
---
> MODULE: svelte/animate
============================================================
FILE: documentation/docs/98-reference/21-svelte-attachments.md
============================================================
---
title: svelte/attachments
tags: attachments
---
> MODULE: svelte/attachments
============================================================
FILE: documentation/docs/98-reference/21-svelte-compiler.md
============================================================
---
title: svelte/compiler
---
> MODULE: svelte/compiler
============================================================
FILE: documentation/docs/98-reference/21-svelte-easing.md
============================================================
---
title: svelte/easing
---
> MODULE: svelte/easing
============================================================
FILE: documentation/docs/98-reference/21-svelte-events.md
============================================================
---
title: svelte/events
---
> MODULE: svelte/events
============================================================
FILE: documentation/docs/98-reference/21-svelte-legacy.md
============================================================
---
title: svelte/legacy
---
This module provides various functions for use during the migration, since some features can't be replaced one to one with new features. All imports are marked as deprecated and should be migrated away from over time.
> MODULE: svelte/legacy
============================================================
FILE: documentation/docs/98-reference/21-svelte-motion.md
============================================================
---
title: svelte/motion
---
> MODULE: svelte/motion
============================================================
FILE: documentation/docs/98-reference/21-svelte-reactivity-window.md
============================================================
---
title: svelte/reactivity/window
---
This module exports reactive versions of various `window` values, each of which has a reactive `current` property that you can reference in reactive contexts (templates, [deriveds]($derived) and [effects]($effect)) without using [``](svelte-window) bindings or manually creating your own event listeners.
```svelte
{innerWidth.current}x{innerHeight.current}
```
> MODULE: svelte/reactivity/window
============================================================
FILE: documentation/docs/98-reference/21-svelte-reactivity.md
============================================================
---
title: svelte/reactivity
---
Svelte provides reactive versions of various built-ins like [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) that can be used just like their native counterparts, as well as a handful of additional utilities for handling reactivity.
> MODULE: svelte/reactivity
============================================================
FILE: documentation/docs/98-reference/21-svelte-server.md
============================================================
---
title: svelte/server
---
> MODULE: svelte/server
============================================================
FILE: documentation/docs/98-reference/21-svelte-store.md
============================================================
---
title: svelte/store
---
> MODULE: svelte/store
============================================================
FILE: documentation/docs/98-reference/21-svelte-transition.md
============================================================
---
title: svelte/transition
tags: transitions
---
> MODULE: svelte/transition
============================================================
FILE: documentation/docs/98-reference/30-compiler-errors.md
============================================================
---
title: 'Compiler errors'
---
@include .generated/compile-errors.md
============================================================
FILE: documentation/docs/98-reference/30-compiler-warnings.md
============================================================
---
title: 'Compiler warnings'
---
Svelte warns you at compile time if it catches potential mistakes, such as writing inaccessible markup.
Some warnings may be incorrect in your concrete use case. You can disable such false positives by placing a `` comment above the line that causes the warning. Example:
```svelte
```
You can list multiple rules in a single comment (separated by commas), and add an explanatory note (in parentheses) alongside them:
```svelte
...
```
@include .generated/compile-warnings.md
============================================================
FILE: documentation/docs/98-reference/30-runtime-errors.md
============================================================
---
title: 'Runtime errors'
---
## Client errors
@include .generated/client-errors.md
## Server errors
@include .generated/server-errors.md
## Shared errors
@include .generated/shared-errors.md
============================================================
FILE: documentation/docs/98-reference/30-runtime-warnings.md
============================================================
---
title: 'Runtime warnings'
---
## Client warnings
@include .generated/client-warnings.md
## Shared warnings
@include .generated/shared-warnings.md
============================================================
FILE: documentation/docs/98-reference/index.md
============================================================
---
title: Reference
---
============================================================
FILE: documentation/docs/99-legacy/00-legacy-overview.md
============================================================
---
title: Overview
---
Svelte 5 introduced some significant changes to Svelte's API, including [runes](what-are-runes), [snippets](snippet) and event attributes. As a result, some Svelte 3/4 features are deprecated (though supported for now, unless otherwise specified) and will eventually be removed. We recommend that you incrementally [migrate your existing code](v5-migration-guide).
The following pages document these features for
- people still using Svelte 3/4
- people using Svelte 5, but with components that haven't yet been migrated
Since Svelte 3/4 syntax still works in Svelte 5, we will distinguish between _legacy mode_ and _runes mode_. Once a component is in runes mode (which you can opt into by using runes, or by explicitly setting the `runes: true` compiler option), legacy mode features are no longer available.
If you're exclusively interested in the Svelte 3/4 syntax, you can browse its documentation at [v4.svelte.dev](https://v4.svelte.dev).
============================================================
FILE: documentation/docs/99-legacy/01-legacy-let.md
============================================================
---
title: Reactive let/var declarations
---
In runes mode, reactive state is explicitly declared with the [`$state` rune]($state).
In legacy mode, variables declared at the top level of a component are automatically considered _reactive_. Reassigning or mutating these variables (`count += 1` or `object.x = y`) will cause the UI to update.
```svelte
count += 1}>
clicks: {count}
```
Because Svelte's legacy mode reactivity is based on _assignments_, using array methods like `.push()` and `.splice()` won't automatically trigger updates. A subsequent assignment is required to 'tell' the compiler to update the UI:
```svelte
```
============================================================
FILE: documentation/docs/99-legacy/02-legacy-reactive-assignments.md
============================================================
---
title: Reactive $: statements
---
In runes mode, reactions to state updates are handled with the [`$derived`]($derived) and [`$effect`]($effect) runes.
In legacy mode, any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with a `$:` [label](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). These statements run after other code in the `
```
Statements are ordered _topologically_ by their dependencies and their assignments: since the `console.log` statement depends on `sum`, `sum` is calculated first even though it appears later in the source.
Multiple statements can be combined by putting them in a block:
```js
// @noErrors
$: {
// recalculate `total` when `items` changes
total = 0;
for (const item of items) {
total += item.value;
}
}
```
The left-hand side of a reactive assignments can be an identifier, or it can be a destructuring assignment:
```js
// @noErrors
$: ({ larry, moe, curly } = stooges);
```
## Understanding dependencies
The dependencies of a `$:` statement are determined at compile time — they are whichever variables are referenced (but not assigned to) inside the statement.
In other words, a statement like this will _not_ re-run when `count` changes, because the compiler cannot 'see' the dependency:
```js
// @noErrors
let count = 0;
let double = () => count * 2;
$: doubled = double();
```
Similarly, topological ordering will fail if dependencies are referenced indirectly: `z` will never update, because `y` is not considered 'dirty' when the update occurs. Moving `$: z = y` below `$: setY(x)` will fix it:
```svelte
```
## Browser-only code
Reactive statements run during server-side rendering as well as in the browser. This means that any code that should only run in the browser must be wrapped in an `if` block:
```js
// @noErrors
$: if (browser) {
document.title = title;
}
```
============================================================
FILE: documentation/docs/99-legacy/03-legacy-export-let.md
============================================================
---
title: export let
---
In runes mode, [component props](basic-markup#Component-props) are declared with the [`$props`]($props) rune, allowing parent components to pass in data.
In legacy mode, props are marked with the `export` keyword, and can have a default value:
```svelte
```
The default value is used if it would otherwise be `undefined` when the component is created.
> [!NOTE] Unlike in runes mode, if the parent component changes a prop from a defined value to `undefined`, it does not revert to the initial value.
Props without default values are considered _required_, and Svelte will print a warning during development if no value is provided, which you can squelch by specifying `undefined` as the default value:
```js
export let foo +++= undefined;+++
```
## Component exports
An exported `const`, `class` or `function` declaration is _not_ considered a prop — instead, it becomes part of the component's API:
```svelte
```
```svelte
greeter.greet('world')}>
greet
```
## Renaming props
The `export` keyword can appear separately from the declaration. This is useful for renaming props, for example in the case of a reserved word:
```svelte
```
============================================================
FILE: documentation/docs/99-legacy/04-legacy-$$props-and-$$restProps.md
============================================================
---
title: $$props and $$restProps
---
In runes mode, getting an object containing all the props that were passed in is easy, using the [`$props`]($props) rune.
In legacy mode, we use `$$props` and `$$restProps`:
- `$$props` contains all the props that were passed in, including ones that are not individually declared with the `export` keyword
- `$$restProps` contains all the props that were passed in _except_ the ones that were individually declared
For example, a `` component might need to pass along all its props to its own `` element, except the `variant` prop:
```svelte
click me
```
In Svelte 3/4 using `$$props` and `$$restProps` creates a modest performance penalty, so they should only be used when needed.
============================================================
FILE: documentation/docs/99-legacy/10-legacy-on.md
============================================================
---
title: on:
---
In runes mode, event handlers are just like any other attribute or prop.
In legacy mode, we use the `on:` directive:
```svelte
count: {count}
```
Handlers can be declared inline with no performance penalty:
```svelte
(count += 1)}>
count: {count}
```
Add _modifiers_ to element event handlers with the `|` character.
```svelte
```
The following modifiers are available:
- `preventDefault` — calls `event.preventDefault()` before running the handler
- `stopPropagation` — calls `event.stopPropagation()`, preventing the event reaching the next element
- `stopImmediatePropagation` — calls `event.stopImmediatePropagation()`, preventing other listeners of the same event from being fired.
- `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
- `nonpassive` — explicitly set `passive: false`
- `capture` — fires the handler during the _capture_ phase instead of the _bubbling_ phase
- `once` — remove the handler after the first time it runs
- `self` — only trigger handler if `event.target` is the element itself
- `trusted` — only trigger handler if `event.isTrusted` is `true`. I.e. if the event is triggered by a user action.
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
If the `on:` directive is used without a value, the component will _forward_ the event, meaning that a consumer of the component can listen for it.
```svelte
The component itself will emit the click event
```
It's possible to have multiple event listeners for the same event:
```svelte
clicks: {count}
```
## Component events
Components can dispatch events by creating a _dispatcher_ when they are initialised:
```svelte
dispatch('decrement')}>decrement dispatch('increment')}>increment
```
`dispatch` creates a [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). If a second argument is provided, it becomes the `detail` property of the event object.
A consumer of this component can listen for the dispatched events:
```svelte
n -= 1}
on:increment={() => n += 1}
/>
n: {n}
```
Component events do not bubble — a parent component can only listen for events on its immediate children.
Other than `once`, modifiers are not valid on component event handlers.
> [!NOTE]
> If you're planning an eventual migration to Svelte 5, use callback props instead. This will make upgrading easier as `createEventDispatcher` is deprecated:
>
> ```svelte
>
>
>
> decrement
> increment
> ```
============================================================
FILE: documentation/docs/99-legacy/20-legacy-slots.md
============================================================
---
title:
---
In Svelte 5, content can be passed to components in the form of [snippets](snippet) and rendered using [render tags](@render).
In legacy mode, content inside component tags is considered _slotted content_, which can be rendered by the component using a `` element:
```svelte
This is some slotted content
```
```svelte
```
> [!NOTE] If you want to render a regular `` element, you can use ``.
## Named slots
A component can have _named_ slots in addition to the default slot. On the parent side, add a `slot="..."` attribute to an element, component or [``](legacy-svelte-fragment) directly inside the component tags.
```svelte
{#if open}
This is some slotted content
+++
+++
open = false}>
close
+++
+++
{/if}
```
On the child side, add a corresponding `` element:
```svelte
++++++
```
## Fallback content
If no slotted content is provided, a component can define fallback content by putting it inside the `` element:
```svelte
This will be rendered if no slotted content is provided
```
## Passing data to slotted content
Slots can be rendered zero or more times and can pass values _back_ to the parent using props. The parent exposes the values to the slot template using the `let:` directive.
```svelte
{#each items as data}
{/each}
```
```svelte
{processed.text}
```
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `` is equivalent to ``.
Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.
```svelte
{#each items as item}
{/each}
```
```svelte
{item.text}
Copyright (c) 2019 Svelte Industries
```
============================================================
FILE: documentation/docs/99-legacy/21-legacy-$$slots.md
============================================================
---
title: $$slots
---
In runes mode, we know which [snippets](snippet) were provided to a component, as they're just normal props.
In legacy mode, the way to know if content was provided for a given slot is with the `$$slots` object, whose keys are the names of the slots passed into the component by the parent.
```svelte
{#if $$slots.description}
{/if}
```
```svelte
Blog Post Title
```
============================================================
FILE: documentation/docs/99-legacy/22-legacy-svelte-fragment.md
============================================================
---
title:
---
The `` element allows you to place content in a [named slot](legacy-slots) without wrapping it in a container DOM element. This keeps the flow layout of your document intact.
```svelte
No header was provided
Some content between header and footer
```
```svelte
Hello
All rights reserved.
Copyright (c) 2019 Svelte Industries
```
> [!NOTE]
> In Svelte 5+, this concept is obsolete, as snippets don't create a wrapping element
============================================================
FILE: documentation/docs/99-legacy/30-legacy-svelte-component.md
============================================================
---
title:
---
In runes mode, `` will re-render if the value of `MyComponent` changes. See the [Svelte 5 migration guide](/docs/svelte/v5-migration-guide#svelte:component-is-no-longer-necessary) for an example.
In legacy mode, it won't — we must use ``, which destroys and recreates the component instance when the value of its `this` expression changes:
```svelte
```
If `this` is falsy, no component is rendered.
============================================================
FILE: documentation/docs/99-legacy/31-legacy-svelte-self.md
============================================================
---
title:
---
The `` element allows a component to include itself, recursively.
It cannot appear at the top level of your markup; it must be inside an if or each block or passed to a component's slot to prevent an infinite loop.
```svelte
{#if count > 0}
counting down... {count}
{:else}
lift-off!
{/if}
```
> [!NOTE]
> This concept is obsolete, as components can import themselves:
> ```svelte
>
>
>
> {#if count > 0}
>
counting down... {count}
>
> {:else}
>
lift-off!
> {/if}
> ```
============================================================
FILE: documentation/docs/99-legacy/40-legacy-component-api.md
============================================================
---
title: Imperative component API
---
In 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 components in a Svelte 5 application.
## Creating a component
```ts
// @noErrors
const component = new Component(options);
```
A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class.
```ts
// @noErrors
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
// assuming App.svelte contains something like
// `export let answer`:
answer: 42
}
});
```
The following initialisation options can be provided:
| option | default | description |
| --------- | ----------- | ---------------------------------------------------------------------------------------------------- |
| `target` | **none** | An `HTMLElement` or `ShadowRoot` to render to. This option is required |
| `anchor` | `null` | A child of `target` to render the component immediately before |
| `props` | `{}` | An object of properties to supply to the component |
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component |
| `hydrate` | `false` | See below |
| `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes |
Existing children of `target` are left where they are.
The `hydrate` option instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. It will only work if the component was compiled with the [`hydratable: true` option](/docs/svelte-compiler#compile). Hydration of `` elements only works properly if the server-side rendering code was also compiled with `hydratable: true`, which adds a marker to each element in the `` so that the component knows which elements it's responsible for removing during hydration.
Whereas children of `target` are normally left alone, `hydrate: true` will cause any children to be removed. For that reason, the `anchor` option cannot be used alongside `hydrate: true`.
The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.
```ts
/// file: index.js
// @noErrors
import App from './App.svelte';
const app = new App({
target: document.querySelector('#server-rendered-html'),
hydrate: true
});
```
> [!NOTE]
> In Svelte 5+, use [`mount`](svelte#mount) instead
## `$set`
```ts
// @noErrors
component.$set(props);
```
Programmatically sets props on an instance. `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `'` string occurrence breaking pages ([#349](https://github.com/sveltejs/svelte/pull/349))
- Allow reference to whitelisted globals without properties ([#333](https://github.com/sveltejs/svelte/pull/333))
- Don't remove ` ` incorrectly ([#348](https://github.com/sveltejs/svelte/issues/348))
- `let` -> `var` in `addCss` block ([#351](https://github.com/sveltejs/svelte/pull/351))
## 1.10.2
- Accept any case for doctype declarations ([#336](https://github.com/sveltejs/svelte/issues/336))
- Allow non-top-level `
```
## 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
## set_context_after_init
> `setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression
This restriction only applies when using the `experimental.async` option, which will be active by default in Svelte 6.
## 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 `$derived(...)`, `$inspect(...)` 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.
## svelte_boundary_reset_onerror
> A `` `reset` function cannot be called while an error is still being handled
If a [``](https://svelte.dev/docs/svelte/svelte-boundary) has an `onerror` function, it must not call the provided `reset` function synchronously since the boundary is still in a broken state. Typically, `reset()` is called later, once the error has been resolved.
If it's possible to resolve the error inside the `onerror` callback, you must at least wait for the boundary to settle before calling `reset()`, for example using [`tick`](https://svelte.dev/docs/svelte/lifecycle-hooks#tick):
```svelte
{
fixTheError();
+++await tick();+++
reset();
}}>
```
============================================================
FILE: packages/svelte/messages/client-warnings/warnings.md
============================================================
## 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);
}
```
## await_reactivity_loss
> Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await`
Svelte's signal-based reactivity works by tracking which bits of state are read when a template or `$derived(...)` expression executes. If an expression contains an `await`, Svelte transforms it such that any state _after_ the `await` is also tracked — in other words, in a case like this...
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
let total = $derived(await a + b);
```
...both `a` and `b` are tracked, even though `b` is only read once `a` has resolved, after the initial execution.
This does _not_ apply to an `await` that is not 'visible' inside the expression. In a case like this...
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
async function sum() {
return await a + b;
}
let total = $derived(await sum());
```
...`total` will depend on `a` (which is read immediately) but not `b` (which is not). The solution is to pass the values into the function:
```js
let a = Promise.resolve(1);
let b = 2;
// ---cut---
/**
* @param {Promise} a
* @param {number} b
*/
async function sum(a, b) {
return await a + b;
}
let total = $derived(await sum(a, b));
```
## await_waterfall
> An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
In a case like this...
```js
async function one() { return 1 }
async function two() { return 2 }
// ---cut---
let a = $derived(await one());
let b = $derived(await two());
```
...the second `$derived` will not be created until the first one has resolved. Since `await two()` does not depend on the value of `a`, this delay, often described as a 'waterfall', is unnecessary.
(Note that if the values of `await one()` and `await two()` subsequently change, they can do so concurrently — the waterfall only occurs when the deriveds are first created.)
You can solve this by creating the promises first and _then_ awaiting them:
```js
async function one() { return 1 }
async function two() { return 2 }
// ---cut---
let aPromise = $derived(one());
let bPromise = $derived(two());
let a = $derived(await aPromise);
let b = $derived(await bPromise);
```
## 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.
## derived_inert
> Reading a derived belonging to a now-destroyed effect may result in stale values
A `$derived` value created inside an effect will stop updating when the effect is destroyed. You should create the `$derived` outside the effect, or inside an `$effect.root`.
## event_handler_invalid
> %handler% should be a function. Did you mean to %suggestion%?
## hydratable_missing_but_expected
> Expected to find a hydratable with key `%key%` during hydration, but did not.
This can happen if you render a hydratable on the client that was not rendered on the server, and means that it was forced to fall back to running its function blockingly during hydration. This is bad for performance, as it blocks hydration until the asynchronous work completes.
```svelte
```
## 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 `