* upstream/master: (190 commits)
invalidate $$props and $$restProps only when there are changes (#5123)
site: use https in link in blog (#5148)
Simplify each block bindings example (#5094)
fix $$props reactive for slots (#5125)
site: add FAQ entry for how to document a svelte component (#5131)
site: remove an obsolete TODO in blog post (#5135)
Increase timeout for unit build
Increase timeout for unit tests
-> v3.24.0
spread condition for input element (#5004)
update changelog
fix(5018): compare wholeText instead of data (#5028)
html anchor in head (#5071)
error on expression scope store (#5079)
update changelog
preprocess self-closing script and style tags (#5082)
update changelog
fix: Parameters with default values are optional (#5083)
make builds time out after a reasonable period (#5100)
site: fix blog typo (#5090)
...
### Before submitting the PR, please make sure you do the following
### Before submitting the PR, please make sure you do the following
- [ ] It's really useful if your PR relates to an outstanding issue, so please reference it in your PR, or create an explanatory one for discussion. In many cases features are absent for a reason.
- [ ] It's really useful if your PR relates to an outstanding issue, so please reference it in your PR, or create an explanatory one for discussion. In many cases, features are absent for a reason.
- [ ] This message body should clearly illustrate what problems it solves. If there are related issues, remember to reference them.
- [ ] This message body should clearly illustrate what problems it solves. If there are related issues, remember to reference them.
- [ ] Ideally, include a test that fails without this PR but passes with it. PRs will only be merged once they pass CI. (Remember to `npm run lint`!)
- [ ] Ideally, include a test that fails without this PR but passes with it. PRs will only be merged once they pass CI. (Remember to `npm run lint`!)
### Tests
### Tests
- [ ] Run the tests tests with `npm test` or `yarn test`)
- [ ] Run the tests with `npm test` or `yarn test`)
* Fix reactivity when passing `$$props` to a `<slot>` ([#3364](https://github.com/sveltejs/svelte/issues/3364))
* Fix unneeded invalidation of `$$props` and `$$restProps` ([#4993](https://github.com/sveltejs/svelte/issues/4993), [#5118](https://github.com/sveltejs/svelte/issues/5118))
## 3.24.0
* Support nullish coalescing (`??`) and optional chaining (`?.`) operators ([#1972](https://github.com/sveltejs/svelte/issues/1972))
* Support `import.meta` ([#4379](https://github.com/sveltejs/svelte/issues/4379))
* Fix only setting `<input>` values when they're changed when there are spread attributes ([#4418](https://github.com/sveltejs/svelte/issues/4418))
* Fix placement of `{@html}` when used at the root of a slot, at the root of a component, or in `<svelte:head>` ([#5012](https://github.com/sveltejs/svelte/issues/5012), [#5071](https://github.com/sveltejs/svelte/pull/5071))
* Fix certain handling of two-way bound `contenteditable` elements ([#5018](https://github.com/sveltejs/svelte/issues/5018))
* Fix handling of `import`ed value that is used as a store and is also mutated ([#5019](https://github.com/sveltejs/svelte/issues/5019))
* Do not display `a11y-missing-content` warning on elements with `contenteditable` bindings ([#5020](https://github.com/sveltejs/svelte/issues/5020))
* Fix handling of `this` in inline function expressions in the template ([#5033](https://github.com/sveltejs/svelte/issues/5033))
* Fix collapsing HTML with static content ([#5040](https://github.com/sveltejs/svelte/issues/5040))
* Prevent use of `$store` at compile time when top-level `store` has been shadowed ([#5048](https://github.com/sveltejs/svelte/issues/5048))
* Update `<select>` with one-way `value` binding when the available `<option>`s change ([#5051](https://github.com/sveltejs/svelte/issues/5051))
* Fix published `tweened` types so the `.set()` and `.update()` options are optional ([#5062](https://github.com/sveltejs/svelte/issues/5062))
* Fix `use:` actions being recreated when a keyed `{#each}` is reordered ([#4693](https://github.com/sveltejs/svelte/issues/4693))
* Fix `{@html}` when using tags that can only appear inside certain tags ([#4852](https://github.com/sveltejs/svelte/issues/4852))
* Fix reactivity when binding directly to `{#each}` context ([#4879](https://github.com/sveltejs/svelte/issues/4879))
## 3.22.3
* Support default values and trailing commas in destructuring `{#await}` ([#4560](https://github.com/sveltejs/svelte/issues/4560), [#4810](https://github.com/sveltejs/svelte/issues/4810))
* Fix handling of `tweened` store when set using `duration: 0` ([#4799](https://github.com/sveltejs/svelte/issues/4799), [#4846](https://github.com/sveltejs/svelte/issues/4846))
* Fix setting `value` attribute with `bind:group` and attribute spread ([#4803](https://github.com/sveltejs/svelte/issues/4803))
* Fix issue with compound `{#if}` block involving static condition, dynamic condition, and inline component ([#4840](https://github.com/sveltejs/svelte/issues/4840))
* Update a11y warnings per ARIA 1.2 working draft ([#4844](https://github.com/sveltejs/svelte/issues/4844))
## 3.22.2
* Fix compiler exception with `a11y-img-redundant-alt` and value-less `alt` attribute ([#4777](https://github.com/sveltejs/svelte/issues/4777))
## 3.22.1
* Fix compiler exception with `a11y-img-redundant-alt` and dynamic `alt` attribute ([#4770](https://github.com/sveltejs/svelte/issues/4770))
## 3.22.0
* Fix misaligned line numbers in source maps ([#3906](https://github.com/sveltejs/svelte/issues/3906))
* Make setting a `tweened` store using `duration: 0` instantly update the value ([#4399](https://github.com/sveltejs/svelte/issues/4399))
* Fix reactivity with imported values that are then mutated ([#4555](https://github.com/sveltejs/svelte/issues/4555))
* Fix variable name conflict with component called `<Anchor>` ([#4768](https://github.com/sveltejs/svelte/issues/4768))
## 3.21.0
* Support dimension bindings in cross-origin environments ([#2147](https://github.com/sveltejs/svelte/issues/2147))
* Fix several related outro bugs ([#3202](https://github.com/sveltejs/svelte/issues/3202), [#3410](https://github.com/sveltejs/svelte/issues/3410), [#3685](https://github.com/sveltejs/svelte/issues/3685), [#4620](https://github.com/sveltejs/svelte/issues/4620), [#4630](https://github.com/sveltejs/svelte/issues/4630))
* Try using `globalThis` rather than `globals` for the benefit of non-Node servers and web workers ([#3561](https://github.com/sveltejs/svelte/issues/3561), [#4545](https://github.com/sveltejs/svelte/issues/4545))
* Support `{#await ... catch ...}` syntax shorthand ([#3623](https://github.com/sveltejs/svelte/issues/3623))
* Fix attaching of JS debugging comments to HTML comments ([#4565](https://github.com/sveltejs/svelte/issues/4565))
* Fix `<svelte:component/>` within `<slot/>` ([#4597](https://github.com/sveltejs/svelte/issues/4597))
* Fix bug with updating simple `{#if}` blocks ([#4629](https://github.com/sveltejs/svelte/issues/4629))
* Fix issues with `<input type="number">` updates ([#4631](https://github.com/sveltejs/svelte/issues/4631), [#4687](https://github.com/sveltejs/svelte/issues/4687))
* Fix `{#if}` block directly within `<slot/>` ([#4703](https://github.com/sveltejs/svelte/issues/4703))
## 3.20.1
* Fix compiler regression with slots ([#4562](https://github.com/sveltejs/svelte/issues/4562))
## 3.20.0
* Allow destructuring in `{#await}` blocks ([#1851](https://github.com/sveltejs/svelte/issues/1851))
* Allow `<svelte:self>` to be used in a slot ([#2798](https://github.com/sveltejs/svelte/issues/2798))
* Expose object of unknown props in `$$restProps` ([#2930](https://github.com/sveltejs/svelte/issues/2930))
* Prevent passing named slots other than from the top level within a component ([#3385](https://github.com/sveltejs/svelte/issues/3385))
* Allow transitions and animations to work within iframes ([#3624](https://github.com/sveltejs/svelte/issues/3624))
* Fix initialising slot fallbacks when unnecessary ([#3763](https://github.com/sveltejs/svelte/issues/3763))
* Disallow binding directly to `const` variables ([#4479](https://github.com/sveltejs/svelte/issues/4479))
* Fix re-attaching event handlers on keyed `{#each}` blocks ([#4491](https://github.com/sveltejs/svelte/issues/4491))
* Fix updating keyed `{#each}` blocks with `{:else}` ([#4536](https://github.com/sveltejs/svelte/issues/4536), [#4549](https://github.com/sveltejs/svelte/issues/4549))
* Fix hydration of top-level content ([#4542](https://github.com/sveltejs/svelte/issues/4542))
## 3.19.2
## 3.19.2
* In `dev` mode, display a runtime warning when a component is passed an unexpected slot ([#1020](https://github.com/sveltejs/svelte/issues/1020), [#1447](https://github.com/sveltejs/svelte/issues/1447))
* In `dev` mode, display a runtime warning when a component is passed an unexpected slot ([#1020](https://github.com/sveltejs/svelte/issues/1020), [#1447](https://github.com/sveltejs/svelte/issues/1447))
@ -93,7 +93,7 @@ Test samples are kept in `/test/xxx/samples` folder.
#### Running tests
#### Running tests
1. To run test, run `npm run test`
1. To run test, run `npm run test`.
1. To run test for a specific feature, you can use the `-g` (aka `--grep`) option. For example, to only run test involving transitions, run `npm run test -- -g transition`.
1. To run test for a specific feature, you can use the `-g` (aka `--grep`) option. For example, to only run test involving transitions, run `npm run test -- -g transition`.
##### Running solo test
##### Running solo test
@ -130,7 +130,7 @@ The core Svelte team will be monitoring for pull requests. Do help us by making
### Code conventions
### Code conventions
- `snake_case` for internal variable names and methods
- `snake_case` for internal variable names and methods.
- `camelCase` for public variable names and methods.
- `camelCase` for public variable names and methods.
To build the compiler, and all the other modules included in the package:
To build the compiler, and all the other modules included in the package:
```bash
```bash
@ -69,14 +64,11 @@ npm run test -- -g transition
## svelte.dev
## svelte.dev
The source code for https://svelte.dev, including all the documentation, lives in the [site](site) directory. The site is built with [Sapper](https://sapper.svelte.dev). To develop locally:
The source code for https://svelte.dev, including all the documentation, lives in the [site](site) directory. The site is built with [Sapper](https://sapper.svelte.dev).
```bash
### Is svelte.dev down?
cd site
npm install && npm run update
npm run dev
```
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).
Start the server with `npm run dev`, and navigate to [localhost:3000](http://localhost:3000).
and navigate to [localhost:3000](http://localhost:3000).
## Using a local copy of Svelte
## Running using the local copy of Svelte
By default, the REPL will fetch the most recent version of Svelte from https://unpkg.com/svelte. When running the site locally, you can also use your local copy of Svelte.
By default, the REPL will fetch the most recent version of Svelte from https://unpkg.com/svelte. When running the site locally, you can also use your local copy of Svelte.
To produce the proper browser-compatible UMD build of the compiler, you will need to run `npm run build` (or `npm run dev`) in the root of this repository with the `PUBLISH` environment variable set to any non-empty string.
To produce the proper browser-compatible UMD build of the compiler, you will need to run `npm run build` (or `npm run dev`) in the root of this repository with the `PUBLISH` environment variable set to any non-empty string:
```bash
git clone https://github.com/sveltejs/svelte.git
cd svelte
npm ci
PUBLISH=1 npm run build
cd site
npm ci
npm run update
npm run dev
```
Then visit the REPL at [localhost:3000/repl?version=local](http://localhost:3000/repl?version=local). Please note that the local REPL only works with `npm run dev` and not when building the site for production usage.
Then visit the REPL at [localhost:3000/repl?version=local](http://localhost:3000/repl?version=local). Please note that the local REPL only works with `npm run dev` and not when building the site for production usage.
@ -35,6 +44,7 @@ In order for the REPL's GitHub integration to work properly when running locally
GITHUB_CLIENT_SECRET=[your app's Client Secret]
GITHUB_CLIENT_SECRET=[your app's Client Secret]
BASEURL=http://localhost:3000
BASEURL=http://localhost:3000
```
```
## Building the site
## Building the site
To build the website, run `npm run sapper`. The output can be found in `__sapper__/build`.
To build the website, run `npm run sapper`. The output can be found in `__sapper__/build`.
@ -30,7 +30,7 @@ Given that, what if the framework *didn't actually run in the browser*? What if,
Svelte is a new framework that does exactly that. You write your components using HTML, CSS and JavaScript (plus a few extra bits you can [learn in under 5 minutes](https://v2.svelte.dev/guide)), and during your build process Svelte compiles them into tiny standalone JavaScript modules. By statically analysing the component template, we can make sure that the browser does as little work as possible.
Svelte is a new framework that does exactly that. You write your components using HTML, CSS and JavaScript (plus a few extra bits you can [learn in under 5 minutes](https://v2.svelte.dev/guide)), and during your build process Svelte compiles them into tiny standalone JavaScript modules. By statically analysing the component template, we can make sure that the browser does as little work as possible.
The [Svelte implementation of TodoMVC](http://svelte-todomvc.surge.sh/) weighs 3.6kb zipped. For comparison, React plus ReactDOM *without any app code* weighs about 45kb zipped. It takes about 10x as long for the browser just to evaluate React as it does for Svelte to be up and running with an interactive TodoMVC.
The [Svelte implementation of TodoMVC](https://svelte-todomvc.surge.sh/) weighs 3.6kb zipped. For comparison, React plus ReactDOM *without any app code* weighs about 45kb zipped. It takes about 10x as long for the browser just to evaluate React as it does for Svelte to be up and running with an interactive TodoMVC.
And once your app *is* up and running, according to [js-framework-benchmark](https://github.com/krausest/js-framework-benchmark) **Svelte is fast as heck**. It's faster than React. It's faster than Vue. It's faster than Angular, or Ember, or Ractive, or Preact, or Riot, or Mithril. It's competitive with Inferno, which is probably the fastest UI framework in the world, for now, because [Dominic Gannaway](https://twitter.com/trueadm) is a wizard. (Svelte is slower at removing elements. We're [working on it](https://github.com/sveltejs/svelte/issues/26).)
And once your app *is* up and running, according to [js-framework-benchmark](https://github.com/krausest/js-framework-benchmark) **Svelte is fast as heck**. It's faster than React. It's faster than Vue. It's faster than Angular, or Ember, or Ractive, or Preact, or Riot, or Mithril. It's competitive with Inferno, which is probably the fastest UI framework in the world, for now, because [Dominic Gannaway](https://twitter.com/trueadm) is a wizard. (Svelte is slower at removing elements. We're [working on it](https://github.com/sveltejs/svelte/issues/26).)
@ -57,7 +57,7 @@ What about a more 'real world' example? Conveniently, the [RealWorld](https://gi
<aside><p>Code-splitting isn't free — if the reference implementation used code-splitting, it would be larger still</p></aside>
<aside><p>Code-splitting isn't free — if the reference implementation used code-splitting, it would be larger still</p></aside>
The entire app costs 132.7kb (39.9kb zipped), which is significantly smaller than the reference React/Redux implementation at 327kb (85.7kb), but even if was as large it would *feel* faster because of code-splitting. And that's a crucial point. We're told we need to code-split our apps, but if your app uses a traditional framework like React or Vue then there's a hard lower bound on the size of your initial code-split chunk — the framework itself, which is likely to be a significant portion of your total app size. With the Svelte approach, that's no longer the case.
The entire app costs 132.7kb (39.9kb zipped), which is significantly smaller than the reference React/Redux implementation at 327kb (85.7kb), but even if it was as large it would *feel* faster because of code-splitting. And that's a crucial point. We're told we need to code-split our apps, but if your app uses a traditional framework like React or Vue then there's a hard lower bound on the size of your initial code-split chunk — the framework itself, which is likely to be a significant portion of your total app size. With the Svelte approach, that's no longer the case.
But size is only part of the story. Svelte apps are also extremely performant and memory-efficient, and the framework includes powerful features that you would sacrifice if you chose a 'minimal' or 'simple' UI library.
But size is only part of the story. Svelte apps are also extremely performant and memory-efficient, and the framework includes powerful features that you would sacrifice if you chose a 'minimal' or 'simple' UI library.
@ -74,8 +74,6 @@ This creates a new directory, `my-svelte-project`, adds files from the [sveltejs
In the `package.json` file, there is a section called `"scripts"`. These scripts define shortcuts for working with your application — `dev`, `build` and `start`. To launch your app in development mode, type the following:
In the `package.json` file, there is a section called `"scripts"`. These scripts define shortcuts for working with your application — `dev`, `build` and `start`. To launch your app in development mode, type the following:
@ -8,7 +8,7 @@ Components are the building blocks of Svelte applications. They are written into
All three sections — script, styles and markup — are optional.
All three sections — script, styles and markup — are optional.
```html
```sv
<script>
<script>
// logic goes here
// logic goes here
</script>
</script>
@ -30,7 +30,7 @@ A `<script>` block contains JavaScript that runs when a component instance is cr
Svelte uses the `export` keyword to mark a variable declaration as a *property* or *prop*, which means it becomes accessible to consumers of the component (see the section on [attributes and props](docs#Attributes_and_props) for more information).
Svelte uses the `export` keyword to mark a variable declaration as a *property* or *prop*, which means it becomes accessible to consumers of the component (see the section on [attributes and props](docs#Attributes_and_props) for more information).
```html
```sv
<script>
<script>
export let foo;
export let foo;
@ -46,7 +46,7 @@ You can specify a default initial value for a prop. It will be used if the compo
In development mode (see the [compiler options](docs#svelte_compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`.
In development mode (see the [compiler options](docs#svelte_compile)), a warning will be printed if no default initial value is provided and the consumer does not specify a value. To squelch this warning, ensure that a default initial value is specified, even if it is `undefined`.
```html
```sv
<script>
<script>
export let bar = 'optional default initial value';
export let bar = 'optional default initial value';
export let baz = undefined;
export let baz = undefined;
@ -57,7 +57,7 @@ In development mode (see the [compiler options](docs#svelte_compile)), a warning
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
If you export a `const`, `class` or `function`, it is readonly from outside the component. Function *expressions* are valid props, however.
```html
```sv
<script>
<script>
// these are readonly
// these are readonly
export const thisIs = 'readonly';
export const thisIs = 'readonly';
@ -75,7 +75,7 @@ If you export a `const`, `class` or `function`, it is readonly from outside the
You can use reserved words as prop names.
You can use reserved words as prop names.
```html
```sv
<script>
<script>
let className;
let className;
@ -95,7 +95,7 @@ Update expressions (`count += 1`) and property assignments (`obj.x = y`) have th
Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. Options for getting around this can be found in the [tutorial](tutorial/updating-arrays-and-objects).
Because Svelte's reactivity is based on assignments, using array methods like `.push()` and `.splice()` won't automatically trigger updates. Options for getting around this can be found in the [tutorial](tutorial/updating-arrays-and-objects).
```html
```sv
<script>
<script>
let count = 0;
let count = 0;
@ -113,7 +113,7 @@ Because Svelte's reactivity is based on assignments, using array methods like `.
Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run immediately before the component updates, whenever the values that they depend on have changed.
Any top-level statement (i.e. not inside a block or a function) can be made reactive by prefixing it with the `$:` [JS label syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label). Reactive statements run immediately before the component updates, whenever the values that they depend on have changed.
```html
```sv
<script>
<script>
export let title;
export let title;
@ -132,7 +132,7 @@ Any top-level statement (i.e. not inside a block or a function) can be made reac
If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf.
If a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a `let` declaration on your behalf.
```html
```sv
<script>
<script>
export let num;
export let num;
@ -157,7 +157,7 @@ Note that the store must be declared at the top level of the component — not i
Local variables (that do not represent store values) must *not* have a `$` prefix.
Local variables (that do not represent store values) must *not* have a `$` prefix.
```html
```sv
<script>
<script>
import { writable } from 'svelte/store';
import { writable } from 'svelte/store';
@ -175,7 +175,7 @@ Local variables (that do not represent store values) must *not* have a `$` prefi
You can create your own stores without relying on [`svelte/store`](docs#svelte_store), by implementing the *store contract*:
You can create your own stores without relying on [`svelte/store`](docs#svelte_store), by implementing the *store contract*:
@ -199,7 +199,7 @@ You cannot `export default`, since the default export is the component itself.
> Variables defined in `module` scripts are not reactive — reassigning them will not trigger a rerender even though the variable itself will update. For values shared between multiple components, consider using a [store](docs#svelte_store).
> Variables defined in `module` scripts are not reactive — reassigning them will not trigger a rerender even though the variable itself will update. For values shared between multiple components, consider using a [store](docs#svelte_store).
```html
```sv
<scriptcontext="module">
<scriptcontext="module">
let totalComponents = 0;
let totalComponents = 0;
@ -225,7 +225,7 @@ CSS inside a `<style>` block will be scoped to that component.
This works by adding a class to affected elements, which is based on a hash of the component styles (e.g. `svelte-123xyz`).
This works by adding a class to affected elements, which is based on a hash of the component styles (e.g. `svelte-123xyz`).
```html
```sv
<style>
<style>
p {
p {
/* this will only affect <p> elements in this component */
/* this will only affect <p> elements in this component */
@ -238,7 +238,7 @@ This works by adding a class to affected elements, which is based on a hash of t
To apply styles to a selector globally, use the `:global(...)` modifier.
To apply styles to a selector globally, use the `:global(...)` modifier.
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a *component*.
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a *component*.
```html
```sv
<script>
<script>
import Widget from './Widget.svelte';
import Widget from './Widget.svelte';
</script>
</script>
@ -26,7 +26,7 @@ A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag
By default, attributes work exactly like their HTML counterparts.
By default, attributes work exactly like their HTML counterparts.
```html
```sv
<divclass="foo">
<divclass="foo">
<buttondisabled>can't touch this</button>
<buttondisabled>can't touch this</button>
</div>
</div>
@ -36,7 +36,7 @@ By default, attributes work exactly like their HTML counterparts.
As in HTML, values may be unquoted.
As in HTML, values may be unquoted.
```html
```sv
<inputtype=checkbox>
<inputtype=checkbox>
```
```
@ -44,7 +44,7 @@ As in HTML, values may be unquoted.
Attribute values can contain JavaScript expressions.
Attribute values can contain JavaScript expressions.
```html
```sv
<ahref="page/{p}">page {p}</a>
<ahref="page/{p}">page {p}</a>
```
```
@ -52,7 +52,7 @@ Attribute values can contain JavaScript expressions.
Or they can *be* JavaScript expressions.
Or they can *be* JavaScript expressions.
```html
```sv
<buttondisabled={!clickable}>...</button>
<buttondisabled={!clickable}>...</button>
```
```
@ -71,7 +71,7 @@ All other attributes are included unless their value is [nullish](https://develo
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
```html
```sv
<buttondisabled="{number !== 42}">...</button>
<buttondisabled="{number !== 42}">...</button>
```
```
@ -79,7 +79,7 @@ An expression might include characters that would cause syntax highlighting to f
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
```html
```sv
<!-- These are equivalent -->
<!-- These are equivalent -->
<buttondisabled={disabled}>...</button>
<buttondisabled={disabled}>...</button>
<button{disabled}>...</button>
<button{disabled}>...</button>
@ -91,7 +91,7 @@ By convention, values passed to components are referred to as *properties* or *p
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
As with elements, `name={name}` can be replaced with the `{name}` shorthand.
```html
```sv
<Widgetfoo={bar}answer={42}text="hello"/>
<Widgetfoo={bar}answer={42}text="hello"/>
```
```
@ -101,7 +101,7 @@ As with elements, `name={name}` can be replaced with the `{name}` shorthand.
An element or component can have multiple spread attributes, interspersed with regular ones.
An element or component can have multiple spread attributes, interspersed with regular ones.
```html
```sv
<Widget{...things}/>
<Widget{...things}/>
```
```
@ -109,10 +109,22 @@ An element or component can have multiple spread attributes, interspersed with r
*`$$props`* references all props that are passed to a component – including ones that are not declared with `export`. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.
*`$$props`* references all props that are passed to a component – including ones that are not declared with `export`. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.
```html
```sv
<Widget{...$$props}/>
<Widget{...$$props}/>
```
```
---
*`$$restProps`* contains only the props which are *not* declared with `export`. It can be used to pass down other unknown attributes to an element in a component.
```html
<input{...$$restProps}>
```
> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable.
---
### Text expressions
### Text expressions
@ -124,7 +136,7 @@ An element or component can have multiple spread attributes, interspersed with r
Text can also contain JavaScript expressions:
Text can also contain JavaScript expressions:
```html
```sv
<h1>Hello {name}!</h1>
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>
<p>{a} + {b} = {a + b}.</p>
```
```
@ -136,7 +148,7 @@ Text can also contain JavaScript expressions:
You can use HTML comments inside components.
You can use HTML comments inside components.
```html
```sv
<!-- this is a comment! -->
<!-- this is a comment! -->
<h1>Hello world</h1>
<h1>Hello world</h1>
```
```
@ -145,7 +157,7 @@ You can use HTML comments inside components.
Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually these are accessibility warnings; make sure that you're disabling them for a good reason.
Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually these are accessibility warnings; make sure that you're disabling them for a good reason.
```html
```sv
<!-- svelte-ignore a11y-autofocus -->
<!-- svelte-ignore a11y-autofocus -->
<inputbind:value={name}autofocus>
<inputbind:value={name}autofocus>
```
```
@ -167,7 +179,7 @@ Comments beginning with `svelte-ignore` disable warnings for the next block of m
Content that is conditionally rendered can be wrapped in an if block.
Content that is conditionally rendered can be wrapped in an if block.
```html
```sv
{#if answer === 42}
{#if answer === 42}
<p>what was the question?</p>
<p>what was the question?</p>
{/if}
{/if}
@ -177,7 +189,7 @@ Content that is conditionally rendered can be wrapped in an if block.
Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause.
Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause.
```html
```sv
{#if porridge.temperature > 100}
{#if porridge.temperature > 100}
<p>too hot!</p>
<p>too hot!</p>
{:else if 80 > porridge.temperature}
{:else if 80 > porridge.temperature}
@ -197,6 +209,9 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
{#each expression as name, index}...{/each}
{#each expression as name, index}...{/each}
```
```
```sv
```sv
{#each expression as name (key)}...{/each}
```
```sv
{#each expression as name, index (key)}...{/each}
{#each expression as name, index (key)}...{/each}
```
```
```sv
```sv
@ -207,7 +222,7 @@ Additional conditions can be added with `{:else if expression}`, optionally endi
Iterating over lists of values can be done with an each block.
Iterating over lists of values can be done with an each block.
```html
```sv
<h1>Shopping list</h1>
<h1>Shopping list</h1>
<ul>
<ul>
{#each items as item}
{#each items as item}
@ -222,7 +237,7 @@ You can use each blocks to iterate over any array or array-like value — that i
An each block can also specify an *index*, equivalent to the second argument in an `array.map(...)` callback:
An each block can also specify an *index*, equivalent to the second argument in an `array.map(...)` callback:
```html
```sv
{#each items as item, i}
{#each items as item, i}
<li>{i + 1}: {item.name} x {item.qty}</li>
<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
{/each}
@ -232,7 +247,12 @@ An each block can also specify an *index*, equivalent to the second argument in
If a *key* expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.
If a *key* expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.
```html
```sv
{#each items as item (item.id)}
<li>{item.name} x {item.qty}</li>
{/each}
<!-- or with additional index value -->
{#each items as item, i (item.id)}
{#each items as item, i (item.id)}
<li>{i + 1}: {item.name} x {item.qty}</li>
<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
{/each}
@ -242,7 +262,7 @@ If a *key* expression is provided — which must uniquely identify each list ite
You can freely use destructuring and rest patterns in each blocks.
You can freely use destructuring and rest patterns in each blocks.
```html
```sv
{#each items as { id, name, qty }, i (id)}
{#each items as { id, name, qty }, i (id)}
<li>{i + 1}: {name} x {qty}</li>
<li>{i + 1}: {name} x {qty}</li>
{/each}
{/each}
@ -260,7 +280,7 @@ You can freely use destructuring and rest patterns in each blocks.
An each block can also have an `{:else}` clause, which is rendered if the list is empty.
An each block can also have an `{:else}` clause, which is rendered if the list is empty.
```html
```sv
{#each todos as todo}
{#each todos as todo}
<p>{todo.text}</p>
<p>{todo.text}</p>
{:else}
{:else}
@ -285,7 +305,7 @@ An each block can also have an `{:else}` clause, which is rendered if the list i
Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected.
Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected.
```html
```sv
{#await promise}
{#await promise}
<!-- promise is pending -->
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
<p>waiting for the promise to resolve...</p>
@ -302,7 +322,7 @@ Await blocks allow you to branch on the three possible states of a Promise — p
The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).
The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).
```html
```sv
{#await promise}
{#await promise}
<!-- promise is pending -->
<!-- promise is pending -->
<p>waiting for the promise to resolve...</p>
<p>waiting for the promise to resolve...</p>
@ -316,7 +336,7 @@ The `catch` block can be omitted if you don't need to render anything when the p
If you don't care about the pending state, you can also omit the initial block.
If you don't care about the pending state, you can also omit the initial block.
```html
```sv
{#await promise then value}
{#await promise then value}
<p>The value is {value}</p>
<p>The value is {value}</p>
{/await}
{/await}
@ -337,7 +357,7 @@ The expression should be valid standalone HTML — `{@html "<div>"}content{@html
> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
> Svelte does not sanitize expressions before injecting HTML. If the data comes from an untrusted source, you must sanitize it, or you are exposing your users to an XSS vulnerability.
```html
```sv
<divclass="blog-post">
<divclass="blog-post">
<h1>{post.title}</h1>
<h1>{post.title}</h1>
{@html post.content}
{@html post.content}
@ -360,7 +380,7 @@ The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the
It accepts a comma-separated list of variable names (not arbitrary expressions).
It accepts a comma-separated list of variable names (not arbitrary expressions).
```html
```sv
<script>
<script>
let user = {
let user = {
firstname: 'Ada',
firstname: 'Ada',
@ -377,7 +397,7 @@ It accepts a comma-separated list of variable names (not arbitrary expressions).
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions).
@ -429,7 +449,7 @@ Use the `on:` directive to listen to DOM events.
Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters.
Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters.
```html
```sv
<buttonon:click="{() => count += 1}">
<buttonon:click="{() => count += 1}">
count: {count}
count: {count}
</button>
</button>
@ -439,7 +459,7 @@ Handlers can be declared inline with no performance penalty. As with attributes,
Add *modifiers* to DOM events with the `|` character.
Add *modifiers* to DOM events with the `|` character.
```html
```sv
<formon:submit|preventDefault={handleSubmit}>
<formon:submit|preventDefault={handleSubmit}>
<!-- the `submit` event's default is prevented,
<!-- the `submit` event's default is prevented,
so the page won't reload -->
so the page won't reload -->
@ -453,6 +473,7 @@ The following modifiers are available:
* `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
* `passive` — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)
* `capture` — fires the handler during the *capture* phase instead of the *bubbling* phase
* `capture` — fires the handler during the *capture* phase instead of the *bubbling* phase
* `once` — remove the handler after the first time it runs
* `once` — remove the handler after the first time it runs
* `self` — only trigger handler if event.target is the element itself
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
Modifiers can be chained together, e.g. `on:click|once|capture={...}`.
@ -460,7 +481,7 @@ 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.
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.
```html
```sv
<buttonon:click>
<buttonon:click>
The component itself will emit the click event
The component itself will emit the click event
</button>
</button>
@ -470,7 +491,7 @@ If the `on:` directive is used without a value, the component will *forward* the
It's possible to have multiple event listeners for the same event:
It's possible to have multiple event listeners for the same event:
```html
```sv
<script>
<script>
let counter = 0;
let counter = 0;
function increment() {
function increment() {
@ -497,7 +518,7 @@ Data ordinarily flows down, from parent to child. The `bind:` directive allows d
The simplest bindings reflect the value of a property, such as `input.value`.
The simplest bindings reflect the value of a property, such as `input.value`.
```html
```sv
<inputbind:value={name}>
<inputbind:value={name}>
<textareabind:value={text}></textarea>
<textareabind:value={text}></textarea>
@ -508,7 +529,7 @@ The simplest bindings reflect the value of a property, such as `input.value`.
If the name matches the value, you can use a shorthand.
If the name matches the value, you can use a shorthand.
```html
```sv
<!-- These are equivalent -->
<!-- These are equivalent -->
<inputbind:value={value}>
<inputbind:value={value}>
<inputbind:value>
<inputbind:value>
@ -518,7 +539,7 @@ If the name matches the value, you can use a shorthand.
Numeric input values are coerced; even though `input.value` is a string as far as the DOM is concerned, Svelte will treat it as a number. If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`.
Numeric input values are coerced; even though `input.value` is a string as far as the DOM is concerned, Svelte will treat it as a number. If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`.
```html
```sv
<inputtype="number"bind:value={num}>
<inputtype="number"bind:value={num}>
<inputtype="range"bind:value={num}>
<inputtype="range"bind:value={num}>
```
```
@ -530,7 +551,7 @@ Numeric input values are coerced; even though `input.value` is a string as far a
A `<select>` value binding corresponds to the `value` property on the selected `<option>`, which can be any value (not just strings, as is normally the case in the DOM).
A `<select>` value binding corresponds to the `value` property on the selected `<option>`, which can be any value (not just strings, as is normally the case in the DOM).
```html
```sv
<selectbind:value={selected}>
<selectbind:value={selected}>
<optionvalue={a}>a</option>
<optionvalue={a}>a</option>
<optionvalue={b}>b</option>
<optionvalue={b}>b</option>
@ -542,7 +563,7 @@ A `<select>` value binding corresponds to the `value` property on the selected `
A `<select multiple>` element behaves similarly to a checkbox group.
A `<select multiple>` element behaves similarly to a checkbox group.
```html
```sv
<selectmultiplebind:value={fillings}>
<selectmultiplebind:value={fillings}>
<optionvalue="Rice">Rice</option>
<optionvalue="Rice">Rice</option>
<optionvalue="Beans">Beans</option>
<optionvalue="Beans">Beans</option>
@ -555,7 +576,7 @@ A `<select multiple>` element behaves similarly to a checkbox group.
When the value of an `<option>` matches its text content, the attribute can be omitted.
When the value of an `<option>` matches its text content, the attribute can be omitted.
```html
```sv
<selectmultiplebind:value={fillings}>
<selectmultiplebind:value={fillings}>
<option>Rice</option>
<option>Rice</option>
<option>Beans</option>
<option>Beans</option>
@ -568,7 +589,7 @@ When the value of an `<option>` matches its text content, the attribute can be o
Elements with the `contenteditable` attribute support `innerHTML` and `textContent` bindings.
Elements with the `contenteditable` attribute support `innerHTML` and `textContent` bindings.
Actions are functions that are called when an element is created. They can return an object with a `destroy` method that is called after the element is unmounted:
Actions are functions that are called when an element is created. They can return an object with a `destroy` method that is called after the element is unmounted:
```html
```sv
<script>
<script>
function foo(node) {
function foo(node) {
// the node has been mounted in the DOM
// the node has been mounted in the DOM
@ -753,7 +777,7 @@ An action can have parameters. If the returned value has an `update` method, it
> Don't worry about the fact that we're redeclaring the `foo` function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition.
> Don't worry about the fact that we're redeclaring the `foo` function for every component instance — Svelte will hoist any functions that don't depend on local state out of the component definition.
A transition is triggered by an element entering or leaving the DOM as a result of a state change.
A transition is triggered by an element entering or leaving the DOM as a result of a state change.
When a block is transitioning out, elements inside the block are kept in the DOM until all current transitions have completed.
When a block is transitioning out, all elements inside the block, including those that do not have their own transitions, are kept in the DOM until every transition in the block has completed.
The `transition:` directive indicates a *bidirectional* transition, which means it can be smoothly reversed while the transition is in progress.
The `transition:` directive indicates a *bidirectional* transition, which means it can be smoothly reversed while the transition is in progress.
```html
```sv
{#if visible}
{#if visible}
<divtransition:fade>
<divtransition:fade>
fades in and out
fades in and out
@ -828,7 +852,7 @@ Like actions, transitions can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```html
```sv
{#if visible}
{#if visible}
<divtransition:fade="{{ duration: 2000 }}">
<divtransition:fade="{{ duration: 2000 }}">
flies in, fades out over two seconds
flies in, fades out over two seconds
@ -846,7 +870,7 @@ The `t` argument passed to `css` is a value between `0` and `1` after the `easin
The function is called repeatedly *before* the transition begins, with different `t` and `u` arguments.
The function is called repeatedly *before* the transition begins, with different `t` and `u` arguments.
```html
```sv
<script>
<script>
import { elasticOut } from 'svelte/easing';
import { elasticOut } from 'svelte/easing';
@ -877,14 +901,14 @@ A custom transition function can also return a `tick` function, which is called
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
```html
```sv
<script>
<script>
export let visible = false;
export let visible = false;
function typewriter(node, { speed = 50 }) {
function typewriter(node, { speed = 50 }) {
const valid = (
const valid = (
node.childNodes.length === 1 &&
node.childNodes.length === 1 &&
node.childNodes[0].nodeType === 3
node.childNodes[0].nodeType === Node.TEXT_NODE
);
);
if (!valid) return {};
if (!valid) return {};
@ -923,7 +947,7 @@ An element with transitions will dispatch the following events in addition to an
* `outrostart`
* `outrostart`
* `outroend`
* `outroend`
```html
```sv
{#if visible}
{#if visible}
<p
<p
transition:fly="{{ y: 200, duration: 2000 }}"
transition:fly="{{ y: 200, duration: 2000 }}"
@ -941,7 +965,7 @@ An element with transitions will dispatch the following events in addition to an
Local transitions only play when the block they belong to is created or destroyed, *not* when parent blocks are created or destroyed.
Local transitions only play when the block they belong to is created or destroyed, *not* when parent blocks are created or destroyed.
```html
```sv
{#if x}
{#if x}
{#if y}
{#if y}
<ptransition:fade>
<ptransition:fade>
@ -990,7 +1014,7 @@ Similar to `transition:`, but only applies to elements entering (`in:`) or leavi
Unlike with `transition:`, transitions applied with `in:` and `out:` are not bidirectional — an in transition will continue to 'play' alongside the out transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
Unlike with `transition:`, transitions applied with `in:` and `out:` are not bidirectional — an in transition will continue to 'play' alongside the out transition, rather than reversing, if the block is outroed while the transition is in progress. If an out transition is aborted, transitions will restart from scratch.
```html
```sv
{#if visible}
{#if visible}
<divin:flyout:fade>
<divin:flyout:fade>
flies in, fades out
flies in, fades out
@ -1039,7 +1063,7 @@ An animation is triggered when the contents of a [keyed each block](docs#each) a
Animations can be used with Svelte's [built-in animation functions](docs#svelte_animate) or [custom animation functions](docs#Custom_animation_functions).
Animations can be used with Svelte's [built-in animation functions](docs#svelte_animate) or [custom animation functions](docs#Custom_animation_functions).
```html
```sv
<!-- When `list` is reordered the animation will run-->
<!-- When `list` is reordered the animation will run-->
{#each list as item, index (item)}
{#each list as item, index (item)}
<lianimate:flip>{item}</li>
<lianimate:flip>{item}</li>
@ -1054,7 +1078,7 @@ As with actions and transitions, animations can have parameters.
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
(The double `{{curlies}}` aren't a special syntax; this is an object literal inside an expression tag.)
```html
```sv
{#each list as item, index (item)}
{#each list as item, index (item)}
<lianimate:flip="{{ delay: 500 }}">{item}</li>
<lianimate:flip="{{ delay: 500 }}">{item}</li>
{/each}
{/each}
@ -1073,7 +1097,7 @@ The `t` argument passed to `css` is a value that goes from `0` and `1` after the
The function is called repeatedly *before* the animation begins, with different `t` and `u` arguments.
The function is called repeatedly *before* the animation begins, with different `t` and `u` arguments.
```html
```sv
<script>
<script>
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -1106,7 +1130,7 @@ A custom animation function can also return a `tick` function, which is called *
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
> If it's possible to use `css` instead of `tick`, do so — CSS animations can run off the main thread, preventing jank on slower devices.
```html
```sv
<script>
<script>
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -1146,7 +1170,7 @@ on:eventname={handler}
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
Components can emit events using [createEventDispatcher](docs#createEventDispatcher), or by forwarding DOM events. Listening for component events looks the same as listening for DOM events:
```html
```sv
<SomeComponenton:whatever={handler}/>
<SomeComponenton:whatever={handler}/>
```
```
@ -1154,7 +1178,7 @@ Components can emit events using [createEventDispatcher](docs#createEventDispatc
As with DOM events, 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.
As with DOM events, 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.
```html
```sv
<SomeComponenton:whatever/>
<SomeComponenton:whatever/>
```
```
@ -1169,7 +1193,7 @@ bind:property={variable}
You can bind to component props using the same syntax as for elements.
You can bind to component props using the same syntax as for elements.
```html
```sv
<Keypadbind:value={pin}/>
<Keypadbind:value={pin}/>
```
```
@ -1185,7 +1209,7 @@ Components also support `bind:this`, allowing you to interact with component ins
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
> Note that we can't do `{cart.empty}` since `cart` is `undefined` when the button is first rendered and throws an error.
```html
```sv
<ShoppingCartbind:this={cart}/>
<ShoppingCartbind:this={cart}/>
<buttonon:click={()=> cart.empty()}>
<buttonon:click={()=> cart.empty()}>
@ -1213,7 +1237,7 @@ Components can have child content, in the same way that elements can.
The content is exposed in the child component using the `<slot>` element, which can contain fallback content that is rendered if no children are provided.
The content is exposed in the child component using the `<slot>` element, which can contain fallback content that is rendered if no children are provided.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<Widget></Widget>
<Widget></Widget>
@ -1235,7 +1259,7 @@ The content is exposed in the child component using the `<slot>` element, which
Named slots allow consumers to target specific areas. They can also have fallback content.
Named slots allow consumers to target specific areas. They can also have fallback content.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<Widget>
<Widget>
<h1slot="header">Hello</h1>
<h1slot="header">Hello</h1>
@ -1258,7 +1282,7 @@ Slots can be rendered zero or more times, and can pass values *back* to the pare
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}`, and `<slot {item}>` is equivalent to `<slot item={item}>`.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<FancyList{items}let:prop={thing}>
<FancyList{items}let:prop={thing}>
<div>{thing.text}</div>
<div>{thing.text}</div>
@ -1278,7 +1302,7 @@ The usual shorthand rules apply — `let:item` is equivalent to `let:item={item}
Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.
Named slots can also expose values. The `let:` directive goes on the element with the `slot` attribute.
```html
```sv
<!-- App.svelte -->
<!-- App.svelte -->
<FancyList{items}>
<FancyList{items}>
<divslot="item"let:item>{item.text}</div>
<divslot="item"let:item>{item.text}</div>
@ -1306,7 +1330,7 @@ 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 if or each block to prevent an infinite loop.
It cannot appear at the top level of your markup; it must be inside an if or each block to prevent an infinite loop.
```html
```sv
<script>
<script>
export let count;
export let count;
</script>
</script>
@ -1331,7 +1355,7 @@ The `<svelte:component>` element renders a component dynamically, using the comp
@ -1349,7 +1373,7 @@ If `this` is falsy, no component is rendered.
The `<svelte:window>` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering.
The `<svelte:window>` element allows you to add event listeners to the `window` object without worrying about removing them when the component is destroyed, or checking for the existence of `window` when server-side rendering.
```html
```sv
<script>
<script>
function handleKeydown(event) {
function handleKeydown(event) {
alert(`pressed the ${event.key} key`);
alert(`pressed the ${event.key} key`);
@ -1373,7 +1397,7 @@ You can also bind to the following properties:
All except `scrollX` and `scrollY` are readonly.
All except `scrollX` and `scrollY` are readonly.
```html
```sv
<svelte:windowbind:scrollY={y}/>
<svelte:windowbind:scrollY={y}/>
```
```
@ -1388,7 +1412,7 @@ All except `scrollX` and `scrollY` are readonly.
As with `<svelte:window>`, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave` which don't fire on `window`.
As with `<svelte:window>`, this element allows you to add listeners to events on `document.body`, such as `mouseenter` and `mouseleave` which don't fire on `window`.
```html
```sv
<svelte:body
<svelte:body
on:mouseenter={handleMouseenter}
on:mouseenter={handleMouseenter}
on:mouseleave={handleMouseleave}
on:mouseleave={handleMouseleave}
@ -1406,7 +1430,7 @@ As with `<svelte:window>`, this element allows you to add listeners to events on
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content.
This element makes it possible to insert elements into `document.head`. During server-side rendering, `head` content is exposed separately to the main `html` content.
@ -22,7 +22,7 @@ The `onMount` function schedules a callback to run as soon as the component has
`onMount` does not run inside a [server-side component](docs#Server-side_component_API).
`onMount` does not run inside a [server-side component](docs#Server-side_component_API).
```html
```sv
<script>
<script>
import { onMount } from 'svelte';
import { onMount } from 'svelte';
@ -36,7 +36,7 @@ The `onMount` function schedules a callback to run as soon as the component has
If a function is returned from `onMount`, it will be called when the component is unmounted.
If a function is returned from `onMount`, it will be called when the component is unmounted.
```html
```sv
<script>
<script>
import { onMount } from 'svelte';
import { onMount } from 'svelte';
@ -50,6 +50,8 @@ If a function is returned from `onMount`, it will be called when the component i
</script>
</script>
```
```
> This behaviour will only work when the function passed to `onMount`*synchronously* returns a value. `async` functions always return a `Promise`, and as such cannot *synchronously* return a function.
#### `beforeUpdate`
#### `beforeUpdate`
```js
```js
@ -62,7 +64,7 @@ Schedules a callback to run immediately before the component is updated after an
> The first time the callback runs will be before the initial `onMount`
> The first time the callback runs will be before the initial `onMount`
Schedules a callback to run immediately after the component has been updated.
Schedules a callback to run immediately after the component has been updated.
```html
```sv
<script>
<script>
import { afterUpdate } from 'svelte';
import { afterUpdate } from 'svelte';
@ -104,7 +106,7 @@ Schedules a callback to run once the component is unmounted.
Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.
Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the only one that runs inside a server-side component.
```html
```sv
<script>
<script>
import { onDestroy } from 'svelte';
import { onDestroy } from 'svelte';
@ -124,7 +126,7 @@ promise: Promise = tick()
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.
```html
```sv
<script>
<script>
import { beforeUpdate, tick } from 'svelte';
import { beforeUpdate, tick } from 'svelte';
@ -148,7 +150,7 @@ Associates an arbitrary `context` object with the current component and the spec
Like lifecycle functions, this must be called during component initialisation.
Like lifecycle functions, this must be called during component initialisation.
```html
```sv
<script>
<script>
import { setContext } from 'svelte';
import { setContext } from 'svelte';
@ -168,7 +170,7 @@ context: any = getContext(key: any)
Retrieves the context that belongs to the closest parent component with the specified `key`. Must be called during component initialisation.
Retrieves the context that belongs to the closest parent component with the specified `key`. Must be called during component initialisation.
```html
```sv
<script>
<script>
import { getContext } from 'svelte';
import { getContext } from 'svelte';
@ -188,7 +190,7 @@ Creates an event dispatcher that can be used to dispatch [component events](docs
Component events created with `createEventDispatcher` create a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) and are not cancellable with `event.preventDefault()`. The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) property and can contain any type of data.
Component events created with `createEventDispatcher` create a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) and are not cancellable with `event.preventDefault()`. The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) property and can contain any type of data.
```html
```sv
<script>
<script>
import { createEventDispatcher } from 'svelte';
import { createEventDispatcher } from 'svelte';
@ -202,7 +204,7 @@ Component events created with `createEventDispatcher` create a [CustomEvent](htt
Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the `detail` property of the event object.
Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the `detail` property of the event object.
@ -287,7 +289,9 @@ The second argument to `readable` is the same as the second argument to `writabl
```js
```js
import { readable } from 'svelte/store';
import { readable } from 'svelte/store';
const time = readable(new Date(), set => {
const time = readable(null, set => {
set(new Date());
const interval = setInterval(() => {
const interval = setInterval(() => {
set(new Date());
set(new Date());
}, 1000);
}, 1000);
@ -413,7 +417,7 @@ Both functions return a Promise that resolves when the tween completes. If the t
Out of the box, Svelte will interpolate between two numbers, two arrays or two objects (as long as the arrays and objects are the same 'shape', and their 'leaf' properties are also numbers).
Out of the box, Svelte will interpolate between two numbers, two arrays or two objects (as long as the arrays and objects are the same 'shape', and their 'leaf' properties are also numbers).
```html
```sv
<script>
<script>
import { tweened } from 'svelte/motion';
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
import { cubicOut } from 'svelte/easing';
@ -452,7 +456,7 @@ $: $size = big ? 100 : 10;
The `interpolate` option allows you to tween between *any* arbitrary values. It must be an `(a, b) => t => value` function, where `a` is the starting value, `b` is the target value, `t` is a number between 0 and 1, and `value` is the result. For example, we can use the [d3-interpolate](https://github.com/d3/d3-interpolate) package to smoothly interpolate between two colours.
The `interpolate` option allows you to tween between *any* arbitrary values. It must be an `(a, b) => t => value` function, where `a` is the starting value, `b` is the target value, `t` is a number between 0 and 1, and `value` is the result. For example, we can use the [d3-interpolate](https://github.com/d3/d3-interpolate) package to smoothly interpolate between two colours.
```html
```sv
<script>
<script>
import { interpolateLab } from 'd3-interpolate';
import { interpolateLab } from 'd3-interpolate';
import { tweened } from 'svelte/motion';
import { tweened } from 'svelte/motion';
@ -499,7 +503,7 @@ Both `set` and `update` can take a second argument — an object with `hard` or
[See a full example on the spring tutorial.](tutorial/spring)
[See a full example on the spring tutorial.](tutorial/spring)
```html
```sv
<script>
<script>
import { spring } from 'svelte/motion';
import { spring } from 'svelte/motion';
@ -521,7 +525,7 @@ $: $size = big ? 100 : 10;
### `svelte/transition`
### `svelte/transition`
The `svelte/transition` module exports six functions: `fade`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with svelte [`transitions`](docs#Transitions).
The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` and `crossfade`. They are for use with Svelte [`transitions`](docs#transition_fn).
#### `fade`
#### `fade`
@ -546,7 +550,7 @@ Animates the opacity of an element from 0 to the current opacity for `in` transi
You can see the `fade` transition in action in the [transition tutorial](tutorial/transition).
You can see the `fade` transition in action in the [transition tutorial](tutorial/transition).
```html
```sv
<script>
<script>
import { fade } from 'svelte/transition';
import { fade } from 'svelte/transition';
</script>
</script>
@ -582,7 +586,7 @@ Animates a `blur` filter alongside an element's opacity.
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `amount` (`number`, default 5) - the size of the blur in pixels
* `amount` (`number`, default 5) - the size of the blur in pixels
```html
```sv
<script>
<script>
import { blur } from 'svelte/transition';
import { blur } from 'svelte/transition';
</script>
</script>
@ -621,7 +625,7 @@ Animates the x and y positions and the opacity of an element. `in` transitions a
You can see the `fly` transition in action in the [transition tutorial](tutorial/adding-parameters-to-transitions).
You can see the `fly` transition in action in the [transition tutorial](tutorial/adding-parameters-to-transitions).
```html
```sv
<script>
<script>
import { fly } from 'svelte/transition';
import { fly } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -656,7 +660,7 @@ Slides an element in and out.
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `duration` (`number`, default 400) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
```html
```sv
<script>
<script>
import { slide } from 'svelte/transition';
import { slide } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -693,7 +697,7 @@ Animates the opacity and scale of an element. `in` transitions animate from an e
* `start` (`number`, default 0) - the scale value to animate out to and in from
* `start` (`number`, default 0) - the scale value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
* `opacity` (`number`, default 0) - the opacity value to animate out to and in from
```html
```sv
<script>
<script>
import { scale } from 'svelte/transition';
import { scale } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -731,7 +735,7 @@ Animates the stroke of an SVG element, like a snake in a tube. `in` transitions
The `speed` parameter is a means of setting the duration of the transition relative to the path's length. It is modifier that is applied to the length of the path: `duration = length / speed`. A path that is 1000 pixels with a speed of 1 will have a duration of `1000ms`, setting the speed to `0.5` will double that duration and setting it to `2` will halve it.
The `speed` parameter is a means of setting the duration of the transition relative to the path's length. It is modifier that is applied to the length of the path: `duration = length / speed`. A path that is 1000 pixels with a speed of 1 will have a duration of `1000ms`, setting the speed to `0.5` will double that duration and setting it to `2` will halve it.
```html
```sv
<script>
<script>
import { draw } from 'svelte/transition';
import { draw } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -758,7 +762,7 @@ The `speed` parameter is a means of setting the duration of the transition relat
### `svelte/animate`
### `svelte/animate`
The `svelte/animate` module exports one function for use with svelte [animations](docs#Animations).
The `svelte/animate` module exports one function for use with Svelte [animations](docs#animate_fn).
#### `flip`
#### `flip`
@ -785,7 +789,7 @@ The `flip` function calculates the start and end position of an element and anim
You can see a full example on the [animations tutorial](tutorial/animate)
You can see a full example on the [animations tutorial](tutorial/animate)
```html
```sv
<script>
<script>
import { flip } from 'svelte/animate';
import { flip } from 'svelte/animate';
import { quintOut } from 'svelte/easing';
import { quintOut } from 'svelte/easing';
@ -804,7 +808,7 @@ You can see a full example on the [animations tutorial](tutorial/animate)
### `svelte/easing`
### `svelte/easing`
Easing functions specificy the rate of change over time and are useful when working with Svelte's built-in transitions and animations as well as the tweened and spring utilities. `svelte/easing` contains 31 named exports, a `linear` ease and 3 variants of 10 different easing functions: `in`, `out` and `inOut`.
Easing functions specify the rate of change over time and are useful when working with Svelte's built-in transitions and animations as well as the tweened and spring utilities. `svelte/easing` contains 31 named exports, a `linear` ease and 3 variants of 10 different easing functions: `in`, `out` and `inOut`.
You can explore the various eases using the [ease visualiser](examples#easing) in the [examples section](examples).
You can explore the various eases using the [ease visualiser](examples#easing) in the [examples section](examples).
@ -973,8 +977,8 @@ app.count += 1;
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](docs#svelte_options).
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](docs#svelte_options).
A number of [community-maintained preprocessing plugins](https://github.com/sveltejs/integrations#preprocessors) are available to allow you to use Svelte with tools like TypeScript, PostCSS, SCSS, and Less.
You can write your own preprocessor using the `svelte.preprocess` API.
question: I'm new to Svelte. Where should I start?
---
We think the best way to get started is playing through the interactive [Tutorial](https://svelte.dev/tutorial). Each step there is mainly focused on one specific aspect and is easy to follow. You'll be editing and running real Svelte components right in your browser.
Five to ten minutes should be enough to get you up and running. An hour and a half should get you through the entire tutorial.
New features aren't being added to it, and bugs will probably only be fixed if they are extremely nasty or present some sort of security vulnerability.
The documentation is still available [here](https://v2.svelte.dev/guide).
You need to install a preprocessor such as [svelte-preprocess](https://github.com/sveltejs/svelte-preprocess). You can run type checking from the command line with [svelte-check](https://www.npmjs.com/package/svelte-check).
To declare the type of a reactive variable in a Svelte template, you should use the following syntax:
There are several UI component libraries. Find them under the [code section](https://svelte-community.netlify.com/code) of the Svelte Community website.
We don't have a good answer to this yet, but it is a priority. There are a few approaches that people take when testing, but it generally involves compiling the component and mounting it to something and then performing the tests.
You essentially need to create a bundle for each component you're testing (since svelte is a compiler and not a normal library) and then mount them. You can mount to a JSDOM instance, or you can use Puppeteer if you need a real browser, or you can use a tool like Cypress. There is an example of this in the Sapper starter template.
You can use any router lib you want. A lot of people use [page.js](https://github.com/visionmedia/page.js). There's also [navaid](https://github.com/lukeed/navaid), which is very similar.
If you prefer a declarative HTML approach, there's [svelte-routing](https://github.com/EmilTholin/svelte-routing).
If you need hash-based routing on the client side, check out [svelte-spa-router](https://github.com/ItalyPaleAle/svelte-spa-router), or [abstract-state-router](https://github.com/TehShrike/abstract-state-router/), a mature router for business software.
For filesystem-based routing, you can take a look at [Routify](https://routify.dev).
For an official solution, there's nothing that's simply a routing library. There is, however, the official [Sapper](https://sapper.svelte.dev/) framework, a Next.js-style application framework built on Svelte, which includes its own filesystem-based routing.
@ -19,4 +19,6 @@ Add a `<script>` tag that imports `Nested.svelte`...
<Nested/>
<Nested/>
```
```
Notice that even though `Nested.svelte` has a `<p>` element, the styles from `App.svelte` don't leak in.
Notice that even though `Nested.svelte` has a `<p>` element, the styles from `App.svelte` don't leak in.
Also notice that the component name `Nested` is capitalised. This convention has been adopted to allow us to differentiate between user-defined components and regular HTML tags.
The `tick` function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
The `tick` function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
When you invalidate component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next *microtask* to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
When you update component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next *microtask* to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
You can see that behaviour in this example. Select a range of text and hit the tab key. Because the `<textarea>` value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end. We can fix this by importing `tick`...
You can see that behaviour in this example. Select a range of text and hit the tab key. Because the `<textarea>` value changes, the current selection is cleared and the cursor jumps, annoyingly, to the end. We can fix this by importing `tick`...