{"blocks":[{"breadcrumbs":["Introduction"],"href":"/docs/introduction","content":"Welcome to the Svelte reference documentation! This is intended as a resource for people who already have some familiarity with Svelte and want to learn more about using it.\n\nIf that's not you (yet), you may prefer to visit the interactive tutorial or the examples before consulting this reference. You can try Svelte online using the REPL. Alternatively, if you'd like a more fully-featured environment, you can try Svelte on StackBlitz.","rank":null},{"breadcrumbs":["Introduction","Start a new project"],"href":"/docs/introduction#start-a-new-project","content":"We recommend using SvelteKit, the official application framework from the Svelte team:\n\nnpm create svelte@latest myapp\ncd myapp\nnpm install\nnpm run devSvelteKit will handle calling the Svelte compiler to convert your .svelte files into .js files that create the DOM and .css files that style it. It also provides all the other pieces you need to build a web application such as a development server, routing, deployment, and SSR support. SvelteKit uses Vite to build your code.","rank":null},{"breadcrumbs":["Introduction","Start a new project","Alternatives to SvelteKit"],"href":"/docs/introduction#start-a-new-project-alternatives-to-sveltekit","content":"If you don't want to use SvelteKit for some reason, you can also use Svelte with Vite (but without SvelteKit) by running npm create vite@latest and selecting the svelte option. With this, npm run build will generate HTML, JS and CSS files inside the dist directory. In most cases, you will probably need to choose a routing library as well.\n\nAlternatively, there are plugins for all the major web bundlers to handle Svelte compilation — which will output .js and .css that you can insert into your HTML — but most others won't handle SSR.","rank":null},{"breadcrumbs":["Introduction","Editor tooling"],"href":"/docs/introduction#editor-tooling","content":"The Svelte team maintains a VS Code extension and there are integrations with various other editors and tools as well.","rank":null},{"breadcrumbs":["Introduction","Getting help"],"href":"/docs/introduction#getting-help","content":"Don't be shy about asking for help in the Discord chatroom! You can also find answers on Stack Overflow.","rank":null},{"breadcrumbs":["Svelte components"],"href":"/docs/svelte-components","content":"Components are the building blocks of Svelte applications. They are written into .svelte files, using a superset of HTML.\n\nAll three sections — script, styles and markup — are optional.\n\n<script>\n    // logic goes here\n</script>\n\n<!-- markup (zero or more items) goes here -->\n\n<style>\n    /* styles go here */\n</style>","rank":null},{"breadcrumbs":["Svelte components","<script>"],"href":"/docs/svelte-components#script","content":"A <script> block contains JavaScript that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup. There are four additional rules:","rank":null},{"breadcrumbs":["Svelte components","<script>","1. export creates a component prop"],"href":"/docs/svelte-components#script-1-export-creates-a-component-prop","content":"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 for more information).\n\n<script>\n    export let foo;\n\n    // Values that are passed in as props\n    // are immediately available\n    console.log({ foo });\n</script>You can specify a default initial value for a prop. It will be used if the component's consumer doesn't specify the prop on the component (or if its initial value is undefined) when instantiating the component. Note that if the values of props are subsequently updated, then any prop whose value is not specified will be set to undefined (rather than its initial value).\n\nIn development mode (see the compiler options), 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.\n\n<script>\n    export let bar = 'optional default initial value';\n    export let baz = undefined;\n</script>If you export a const, class or function, it is readonly from outside the component. Functions are valid prop values, however, as shown below.\n\n<!--- file: App.svelte --->\n<script>\n    // these are readonly\n    export const thisIs = 'readonly';\n\n    /** @param {string} name */\n    export function greet(name) {\n        alert(`hello ${name}!`);\n    }\n\n    // this is a prop\n    export let format = (n) => n.toFixed(2);\n</script>Readonly props can be accessed as properties on the element, tied to the component using bind:this syntax.\n\nYou can use reserved words as prop names.\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {string} */\n    let className;\n\n    // creates a `class` property, even\n    // though it is a reserved word\n    export { className as class };\n</script>","rank":null},{"breadcrumbs":["Svelte components","<script>","2. Assignments are 'reactive'"],"href":"/docs/svelte-components#script-2-assignments-are-reactive","content":"To change component state and trigger a re-render, just assign to a locally declared variable.\n\nUpdate expressions (count += 1) and property assignments (obj.x = y) have the same effect.\n\n<script>\n    let count = 0;\n\n    function handleClick() {\n        // calling this function will trigger an\n        // update if the markup references `count`\n        count = count + 1;\n    }\n</script>Because Svelte's reactivity is based on assignments, using array methods like .push() and .splice() won't automatically trigger updates. A subsequent assignment is required to trigger the update. This and more details can also be found in the tutorial.\n\n<script>\n    let arr = [0, 1];\n\n    function handleClick() {\n        // this method call does not trigger an update\n        arr.push(2);\n        // this assignment will trigger an update\n        // if the markup references `arr`\n        arr = arr;\n    }\n</script>Svelte's <script> blocks are run only when the component is created, so assignments within a <script> block are not automatically run again when a prop updates. If you'd like to track changes to a prop, see the next example in the following section.\n\n<script>\n    export let person;\n    // this will only set `name` on component creation\n    // it will not update when `person` does\n    let { name } = person;\n</script>","rank":null},{"breadcrumbs":["Svelte components","<script>","3. $: marks a statement as reactive"],"href":"/docs/svelte-components#script-3-$-marks-a-statement-as-reactive","content":"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. Reactive statements run after other script code and before the component markup is rendered, whenever the values that they depend on have changed.\n\n<script>\n    export let title;\n    export let person;\n\n    // this will update `document.title` whenever\n    // the `title` prop changes\n    $: document.title = title;\n\n    $: {\n        console.log(`multiple statements can be combined`);\n        console.log(`the current title is ${title}`);\n    }\n\n    // this will update `name` when 'person' changes\n    $: ({ name } = person);\n\n    // don't do this. it will run before the previous line\n    let name2 = name;\n</script>Only values which directly appear within the $: block will become dependencies of the reactive statement. For example, in the code below total will only update when x changes, but not y.\n\n<!--- file: App.svelte --->\n<script>\n    let x = 0;\n    let y = 0;\n\n    /** @param {number} value */\n    function yPlusAValue(value) {\n        return value + y;\n    }\n\n    $: total = yPlusAValue(x);\n</script>\n\nTotal: {total}\n<button on:click={() => x++}> Increment X </button>\n\n<button on:click={() => y++}> Increment Y </button>It is important to note that the reactive blocks are ordered via simple static analysis at compile time, and all the compiler looks at are the variables that are assigned to and used within the block itself, not in any functions called by them. This means that yDependent will not be updated when x is updated in the following example:\n\n<!--- file: App.svelte --->\n<script>\n    let x = 0;\n    let y = 0;\n\n    /** @param {number} value */\n    function setY(value) {\n        y = value;\n    }\n\n    $: yDependent = y;\n    $: setY(x);\n</script>Moving the line $: yDependent = y below $: setY(x) will cause yDependent to be updated when x is updated.\n\nIf a statement consists entirely of an assignment to an undeclared variable, Svelte will inject a let declaration on your behalf.\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {number} */\n    export let num;\n\n    // we don't need to declare `squared` and `cubed`\n    // — Svelte does it for us\n    $: squared = num * num;\n    $: cubed = squared * num;\n</script>","rank":null},{"breadcrumbs":["Svelte components","<script>","4. Prefix stores with $ to access their values"],"href":"/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values","content":"A store is an object that allows reactive access to a value via a simple store contract. The svelte/store module contains minimal store implementations which fulfil this contract.\n\nAny time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.\n\nAssignments to $-prefixed variables require that the variable be a writable store, and will result in a call to the store's .set method.\n\nNote that the store must be declared at the top level of the component — not inside an if block or a function, for example.\n\nLocal variables (that do not represent store values) must not have a $ prefix.\n\n<script>\n    import { writable } from 'svelte/store';\n\n    const count = writable(0);\n    console.log($count); // logs 0\n\n    count.set(1);\n    console.log($count); // logs 1\n\n    $count = 2;\n    console.log($count); // logs 2\n</script>","rank":null},{"breadcrumbs":["Svelte components","<script>","Store contract"],"href":"/docs/svelte-components#script-store-contract","content":"// @noErrors\nstore = { subscribe: (subscription: (value: any) => void) => (() => void), set?: (value: any) => void }You can create your own stores without relying on svelte/store, by implementing the store contract:\n\nA store must contain a .subscribe method, which must accept as its argument a subscription function. This subscription function must be immediately and synchronously called with the store's current value upon calling .subscribe. All of a store's active subscription functions must later be synchronously called whenever the store's value changes.\nThe .subscribe method must return an unsubscribe function. Calling an unsubscribe function must stop its subscription, and its corresponding subscription function must not be called again by the store.\nA store may optionally contain a .set method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. Such a store is called a writable store.\n\nFor interoperability with RxJS Observables, the .subscribe method is also allowed to return an object with an .unsubscribe method, rather than return the unsubscription function directly. Note however that unless .subscribe synchronously calls the subscription (which is not required by the Observable spec), Svelte will see the value of the store as undefined until it does.","rank":null},{"breadcrumbs":["Svelte components","<script context=\"module\">"],"href":"/docs/svelte-components#script-context-module","content":"A <script> tag with a context=&quot;module&quot; attribute runs once when the module first evaluates, rather than for each component instance. Values declared in this block are accessible from a regular <script> (and the component markup) but not vice versa.\n\nYou can export bindings from this block, and they will become exports of the compiled module.\n\nYou cannot export default, since the default export is the component itself.\n\nVariables 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.\n\n\n<script context=\"module\">\n    let totalComponents = 0;\n\n    // the export keyword allows this function to be imported with e.g.\n    // `import Example, { alertTotal } from './Example.svelte'`\n    export function alertTotal() {\n        alert(totalComponents);\n    }\n</script>\n\n<script>\n    totalComponents += 1;\n    console.log(`total number of times this component has been created: ${totalComponents}`);\n</script>","rank":null},{"breadcrumbs":["Svelte components","<style>"],"href":"/docs/svelte-components#style","content":"CSS inside a <style> block will be scoped to that component.\n\nThis works by adding a class to affected elements, which is based on a hash of the component styles (e.g. svelte-123xyz).\n\n<style>\n    p {\n        /* this will only affect <p> elements in this component */\n        color: burlywood;\n    }\n</style>To apply styles to a selector globally, use the :global(...) modifier.\n\n<style>\n    :global(body) {\n        /* this will apply to <body> */\n        margin: 0;\n    }\n\n    div :global(strong) {\n        /* this will apply to all <strong> elements, in any\n             component, that are inside <div> elements belonging\n             to this component */\n        color: goldenrod;\n    }\n\n    p:global(.red) {\n        /* this will apply to all <p> elements belonging to this\n             component with a class of red, even if class=\"red\" does\n             not initially appear in the markup, and is instead\n             added at runtime. This is useful when the class\n             of the element is dynamically applied, for instance\n             when updating the element's classList property directly. */\n    }\n</style>If you want to make @keyframes that are accessible globally, you need to prepend your keyframe names with -global-.\n\nThe -global- part will be removed when compiled, and the keyframe then be referenced using just my-animation-name elsewhere in your code.\n\n<style>\n    @keyframes -global-my-animation-name {\n        /* code goes here */\n    }\n</style>There should only be 1 top-level <style> tag per component.\n\nHowever, it is possible to have <style> tag nested inside other elements or logic blocks.\n\nIn that case, the <style> tag will be inserted as-is into the DOM, no scoping or processing will be done on the <style> tag.\n\n<div>\n    <style>\n        /* this style tag will be inserted as-is */\n        div {\n            /* this will apply to all `<div>` elements in the DOM */\n            color: red;\n        }\n    </style>\n</div>","rank":null},{"breadcrumbs":["Basic markup"],"href":"/docs/basic-markup","content":"","rank":null},{"breadcrumbs":["Basic markup","Tags"],"href":"/docs/basic-markup#tags","content":"A lowercase tag, like <div>, denotes a regular HTML element. A capitalised tag, such as <Widget> or <Namespace.Widget>, indicates a component.\n\n<script>\n    import Widget from './Widget.svelte';\n</script>\n\n<div>\n    <Widget />\n</div>","rank":null},{"breadcrumbs":["Basic markup","Attributes and props"],"href":"/docs/basic-markup#attributes-and-props","content":"By default, attributes work exactly like their HTML counterparts.\n\n<div class=\"foo\">\n    <button disabled>can't touch this</button>\n</div>As in HTML, values may be unquoted.\n\n\n<input type=checkbox />Attribute values can contain JavaScript expressions.\n\n<a href=\"page/{p}\">page {p}</a>Or they can be JavaScript expressions.\n\n<button disabled={!clickable}>...</button>Boolean attributes are included on the element if their value is truthy and excluded if it's falsy.\n\nAll other attributes are included unless their value is nullish (null or undefined).\n\n<input required={false} placeholder=\"This input field is not required\" />\n<div title={null}>This div has no title attribute</div>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:\n\n\n<button disabled=\"{number !== 42}\">...</button>When the attribute name and value match (name={name}), they can be replaced with {name}.\n\n<button {disabled}>...</button>\n<!-- equivalent to\n<button disabled={disabled}>...</button>\n-->By convention, values passed to components are referred to as properties or props rather than attributes, which are a feature of the DOM.\n\nAs with elements, name={name} can be replaced with the {name} shorthand.\n\n<Widget foo={bar} answer={42} text=\"hello\" />Spread attributes allow many attributes or properties to be passed to an element or component at once.\n\nAn element or component can have multiple spread attributes, interspersed with regular ones.\n\n<Widget {...things} />$$props references all props that are passed to a component, including ones that are not declared with export. Using $$props will not perform as well as references to a specific prop because changes to any prop will cause Svelte to recheck all usages of $$props. But it can be useful in some cases – for example, when you don't know at compile time what props might be passed to a component.\n\n<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. It shares the same performance characteristics compared to specific property access as $$props.\n\n<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.\n\n\nSometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, <input type=&quot;range&quot; min=&quot;0&quot; max=&quot;1&quot; value={0.5} step=&quot;0.1&quot;/>, Svelte will attempt to set the value to 1 (rounding up from 0.5 as the step by default is 1), and then set the step to 0.1. To fix this, change it to <input type=&quot;range&quot; min=&quot;0&quot; max=&quot;1&quot; step=&quot;0.1&quot; value={0.5}/>.\n\n\nAnother example is <img src=&quot;...&quot; loading=&quot;lazy&quot; />. Svelte will set the img src before making the img element loading=&quot;lazy&quot;, which is probably too late. Change this to <img loading=&quot;lazy&quot; src=&quot;...&quot;> to make the image lazily loaded.","rank":null},{"breadcrumbs":["Basic markup","Text expressions"],"href":"/docs/basic-markup#text-expressions","content":"A JavaScript expression can be included as text by surrounding it with curly braces.\n\n{expression}Curly braces can be included in a Svelte template by using their HTML entity strings: &amp;lbrace;, &amp;lcub;, or &amp;#123; for { and &amp;rbrace;, &amp;rcub;, or &amp;#125; for }.\n\nIf you're using a regular expression (RegExp) literal notation, you'll need to wrap it in parentheses.\n\n\n\n<h1>Hello {name}!</h1>\n<p>{a} + {b} = {a + b}.</p>\n\n<div>{(/^[A-Za-z ]+$/).test(value) ? x : y}</div>","rank":null},{"breadcrumbs":["Basic markup","Comments"],"href":"/docs/basic-markup#comments","content":"You can use HTML comments inside components.\n\n<!-- this is a comment! --><h1>Hello world</h1>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.\n\n<!-- svelte-ignore a11y-autofocus -->\n<input bind:value={name} autofocus />","rank":null},{"breadcrumbs":["Logic blocks"],"href":"/docs/logic-blocks","content":"","rank":null},{"breadcrumbs":["Logic blocks","{#if ...}"],"href":"/docs/logic-blocks#if","content":"<!--- copy: false  --->\n{#if expression}...{/if}<!--- copy: false  --->\n{#if expression}...{:else if expression}...{/if}<!--- copy: false  --->\n{#if expression}...{:else}...{/if}Content that is conditionally rendered can be wrapped in an if block.\n\n{#if answer === 42}\n    <p>what was the question?</p>\n{/if}Additional conditions can be added with {:else if expression}, optionally ending in an {:else} clause.\n\n{#if porridge.temperature > 100}\n    <p>too hot!</p>\n{:else if 80 > porridge.temperature}\n    <p>too cold!</p>\n{:else}\n    <p>just right!</p>\n{/if}(Blocks don't have to wrap elements, they can also wrap text within elements!)","rank":null},{"breadcrumbs":["Logic blocks","{#each ...}"],"href":"/docs/logic-blocks#each","content":"<!--- copy: false  --->\n{#each expression as name}...{/each}<!--- copy: false  --->\n{#each expression as name, index}...{/each}<!--- copy: false  --->\n{#each expression as name (key)}...{/each}<!--- copy: false  --->\n{#each expression as name, index (key)}...{/each}<!--- copy: false  --->\n{#each expression as name}...{:else}...{/each}Iterating over lists of values can be done with an each block.\n\n<h1>Shopping list</h1>\n<ul>\n    {#each items as item}\n        <li>{item.name} x {item.qty}</li>\n    {/each}\n</ul>You can use each blocks to iterate over any array or array-like value — that is, any object with a length property.\n\nAn each block can also specify an index, equivalent to the second argument in an array.map(...) callback:\n\n{#each items as item, i}\n    <li>{i + 1}: {item.name} x {item.qty}</li>\n{/each}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.\n\n{#each items as item (item.id)}\n    <li>{item.name} x {item.qty}</li>\n{/each}\n\n<!-- or with additional index value -->\n{#each items as item, i (item.id)}\n    <li>{i + 1}: {item.name} x {item.qty}</li>\n{/each}You can freely use destructuring and rest patterns in each blocks.\n\n{#each items as { id, name, qty }, i (id)}\n    <li>{i + 1}: {name} x {qty}</li>\n{/each}\n\n{#each objects as { id, ...rest }}\n    <li><span>{id}</span><MyComponent {...rest} /></li>\n{/each}\n\n{#each items as [id, ...rest]}\n    <li><span>{id}</span><MyComponent values={rest} /></li>\n{/each}An each block can also have an {:else} clause, which is rendered if the list is empty.\n\n{#each todos as todo}\n    <p>{todo.text}</p>\n{:else}\n    <p>No tasks today!</p>\n{/each}Since Svelte 4 it is possible to iterate over iterables like Map or Set. Iterables need to be finite and static (they shouldn't change while being iterated over). Under the hood, they are transformed to an array using Array.from before being passed off to rendering. If you're writing performance-sensitive code, try to avoid iterables and use regular arrays as they are more performant.","rank":null},{"breadcrumbs":["Logic blocks","{#await ...}"],"href":"/docs/logic-blocks#await","content":"<!--- copy: false  --->\n{#await expression}...{:then name}...{:catch name}...{/await}<!--- copy: false  --->\n{#await expression}...{:then name}...{/await}<!--- copy: false  --->\n{#await expression then name}...{/await}<!--- copy: false  --->\n{#await expression catch name}...{/await}Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected.\nIn SSR mode, only the pending branch will be rendered on the server.\nIf the provided expression is not a Promise only the fulfilled branch will be rendered, including in SSR mode.\n\n{#await promise}\n    <!-- promise is pending -->\n    <p>waiting for the promise to resolve...</p>\n{:then value}\n    <!-- promise was fulfilled or not a Promise -->\n    <p>The value is {value}</p>\n{:catch error}\n    <!-- promise was rejected -->\n    <p>Something went wrong: {error.message}</p>\n{/await}The catch block can be omitted if you don't need to render anything when the promise rejects (or no error is possible).\n\n{#await promise}\n    <!-- promise is pending -->\n    <p>waiting for the promise to resolve...</p>\n{:then value}\n    <!-- promise was fulfilled -->\n    <p>The value is {value}</p>\n{/await}If you don't care about the pending state, you can also omit the initial block.\n\n{#await promise then value}\n    <p>The value is {value}</p>\n{/await}Similarly, if you only want to show the error state, you can omit the then block.\n\n{#await promise catch error}\n    <p>The error is {error}</p>\n{/await}","rank":null},{"breadcrumbs":["Logic blocks","{#key ...}"],"href":"/docs/logic-blocks#key","content":"<!--- copy: false  --->\n{#key expression}...{/key}Key blocks destroy and recreate their contents when the value of an expression changes.\n\nThis is useful if you want an element to play its transition whenever a value changes.\n\n{#key value}\n    <div transition:fade>{value}</div>\n{/key}When used around components, this will cause them to be reinstantiated and reinitialised.\n\n{#key value}\n    <Component />\n{/key}","rank":null},{"breadcrumbs":["Special tags"],"href":"/docs/special-tags","content":"","rank":null},{"breadcrumbs":["Special tags","{@html ...}"],"href":"/docs/special-tags#html","content":"<!--- copy: false --->\n{@html expression}In a text expression, characters like < and > are escaped; however, with HTML expressions, they're not.\n\nThe expression should be valid standalone HTML — {@html &quot;<div>&quot;}content{@html &quot;</div>&quot;} will not work, because </div> is not valid HTML. It also will not compile Svelte code.\n\nSvelte 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\n\n\n<div class=\"blog-post\">\n    <h1>{post.title}</h1>\n    {@html post.content}\n</div>","rank":null},{"breadcrumbs":["Special tags","{@debug ...}"],"href":"/docs/special-tags#debug","content":"<!--- copy: false --->\n{@debug}<!--- copy: false --->\n{@debug var1, var2, ..., varN}The {@debug ...} tag offers an alternative to console.log(...). It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open.\n\n<script>\n    let user = {\n        firstname: 'Ada',\n        lastname: 'Lovelace'\n    };\n</script>\n\n{@debug user}\n\n<h1>Hello {user.firstname}!</h1>{@debug ...} accepts a comma-separated list of variable names (not arbitrary expressions).\n\n<!-- Compiles -->\n{@debug user}\n{@debug user1, user2, user3}\n\n<!-- WON'T compile -->\n{@debug user.firstname}\n{@debug myArray[0]}\n{@debug !isReady}\n{@debug typeof user === 'object'}The {@debug} tag without any arguments will insert a debugger statement that gets triggered when any state changes, as opposed to the specified variables.","rank":null},{"breadcrumbs":["Special tags","{@const ...}"],"href":"/docs/special-tags#const","content":"<!--- copy: false --->\n{@const assignment}The {@const ...} tag defines a local constant.\n\n<script>\n    export let boxes;\n</script>\n\n{#each boxes as box}\n    {@const area = box.width * box.height}\n    {box.width} * {box.height} = {area}\n{/each}{@const} is only allowed as direct child of {#if}, {:else if}, {:else}, {#each}, {:then}, {:catch}, <Component /> or <svelte:fragment />.","rank":null},{"breadcrumbs":["Element directives"],"href":"/docs/element-directives","content":"As well as attributes, elements can have directives, which control the element's behaviour in some way.","rank":null},{"breadcrumbs":["Element directives","on:eventname"],"href":"/docs/element-directives#on-eventname","content":"<!--- copy: false --->\non:eventname={handler}<!--- copy: false --->\non:eventname|modifiers={handler}Use the on: directive to listen to DOM events.\n\n<!--- file: App.svelte --->\n<script>\n    let count = 0;\n\n    /** @param {MouseEvent} event */\n    function handleClick(event) {\n        count += 1;\n    }\n</script>\n\n<button on:click={handleClick}>\n    count: {count}\n</button>Handlers can be declared inline with no performance penalty. As with attributes, directive values may be quoted for the sake of syntax highlighters.\n\n<button on:click={() => (count += 1)}>\n    count: {count}\n</button>Add modifiers to DOM events with the | character.\n\n<form on:submit|preventDefault={handleSubmit}>\n    <!-- the `submit` event's default is prevented,\n         so the page won't reload -->\n</form>The following modifiers are available:\n\npreventDefault — calls event.preventDefault() before running the handler\nstopPropagation — calls event.stopPropagation(), preventing the event reaching the next element\nstopImmediatePropagation - calls event.stopImmediatePropagation(), preventing other listeners of the same event from being fired.\npassive — improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)\nnonpassive — explicitly set passive: false\ncapture — fires the handler during the capture phase instead of the bubbling phase\nonce — remove the handler after the first time it runs\nself — only trigger handler if event.target is the element itself\ntrusted — only trigger handler if event.isTrusted is true. I.e. if the event is triggered by a user action.\n\nModifiers can be chained together, e.g. on:click|once|capture={...}.\n\nIf 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.\n\n<button on:click> The component itself will emit the click event </button>It's possible to have multiple event listeners for the same event:\n\n<!--- file: App.svelte --->\n<script>\n    let counter = 0;\n    function increment() {\n        counter = counter + 1;\n    }\n\n    /** @param {MouseEvent} event */\n    function track(event) {\n        trackEvent(event);\n    }\n</script>\n\n<button on:click={increment} on:click={track}>Click me!</button>","rank":null},{"breadcrumbs":["Element directives","bind:property"],"href":"/docs/element-directives#bind-property","content":"<!--- copy: false --->\nbind:property={variable}Data ordinarily flows down, from parent to child. The bind: directive allows data to flow the other way, from child to parent. Most bindings are specific to particular elements.\n\nThe simplest bindings reflect the value of a property, such as input.value.\n\n<input bind:value={name} />\n<textarea bind:value={text} />\n\n<input type=\"checkbox\" bind:checked={yes} />If the name matches the value, you can use a shorthand.\n\n<input bind:value />\n<!-- equivalent to\n<input bind:value={value} />\n-->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=&quot;number&quot;), the value is null.\n\n<input type=\"number\" bind:value={num} />\n<input type=\"range\" bind:value={num} />On <input> elements with type=&quot;file&quot;, you can use bind:files to get the FileList of selected files. It is readonly.\n\n<label for=\"avatar\">Upload a picture:</label>\n<input accept=\"image/png, image/jpeg\" bind:files id=\"avatar\" name=\"avatar\" type=\"file\" />If you're using bind: directives together with on: directives, the order that they're defined in affects the value of the bound variable when the event handler is called.\n\n<script>\n    let value = 'Hello World';\n</script>\n\n<input\n    on:input={() => console.log('Old value:', value)}\n    bind:value\n    on:input={() => console.log('New value:', value)}\n/>Here we were binding to the value of a text input, which uses the input event. Bindings on other elements may use different events such as change.","rank":null},{"breadcrumbs":["Element directives","Binding <select> value"],"href":"/docs/element-directives#binding-select-value","content":"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).\n\n<select bind:value={selected}>\n    <option value={a}>a</option>\n    <option value={b}>b</option>\n    <option value={c}>c</option>\n</select>A <select multiple> element behaves similarly to a checkbox group. The bound variable is an array with an entry corresponding to the value property of each selected <option>.\n\n<select multiple bind:value={fillings}>\n    <option value=\"Rice\">Rice</option>\n    <option value=\"Beans\">Beans</option>\n    <option value=\"Cheese\">Cheese</option>\n    <option value=\"Guac (extra)\">Guac (extra)</option>\n</select>When the value of an <option> matches its text content, the attribute can be omitted.\n\n<select multiple bind:value={fillings}>\n    <option>Rice</option>\n    <option>Beans</option>\n    <option>Cheese</option>\n    <option>Guac (extra)</option>\n</select>Elements with the contenteditable attribute support the following bindings:\n\ninnerHTML\ninnerText\ntextContent\n\nThere are slight differences between each of these, read more about them here.\n\n\n\n<div contenteditable=\"true\" bind:innerHTML={html} /><details> elements support binding to the open property.\n\n<details bind:open={isOpen}>\n    <summary>Details</summary>\n    <p>Something small enough to escape casual notice.</p>\n</details>","rank":null},{"breadcrumbs":["Element directives","Media element bindings"],"href":"/docs/element-directives#media-element-bindings","content":"Media elements (<audio> and <video>) have their own set of bindings — seven readonly ones...\n\nduration (readonly) — the total duration of the video, in seconds\nbuffered (readonly) — an array of {start, end} objects\nplayed (readonly) — ditto\nseekable (readonly) — ditto\nseeking (readonly) — boolean\nended (readonly) — boolean\nreadyState (readonly) — number between (and including) 0 and 4\n\n...and five two-way bindings:\n\ncurrentTime — the current playback time in the video, in seconds\nplaybackRate — how fast or slow to play the video, where 1 is 'normal'\npaused — this one should be self-explanatory\nvolume — a value between 0 and 1\nmuted — a boolean value indicating whether the player is muted\n\nVideos additionally have readonly videoWidth and videoHeight bindings.\n\n<video\n    src={clip}\n    bind:duration\n    bind:buffered\n    bind:played\n    bind:seekable\n    bind:seeking\n    bind:ended\n    bind:readyState\n    bind:currentTime\n    bind:playbackRate\n    bind:paused\n    bind:volume\n    bind:muted\n    bind:videoWidth\n    bind:videoHeight\n/>","rank":null},{"breadcrumbs":["Element directives","Image element bindings"],"href":"/docs/element-directives#image-element-bindings","content":"Image elements (<img>) have two readonly bindings:\n\nnaturalWidth (readonly) — the original width of the image, available after the image has loaded\nnaturalHeight (readonly) — the original height of the image, available after the image has loaded\n\n<img\n    bind:naturalWidth\n    bind:naturalHeight\n></img>","rank":null},{"breadcrumbs":["Element directives","Block-level element bindings"],"href":"/docs/element-directives#block-level-element-bindings","content":"Block-level elements have 4 read-only bindings, measured using a technique similar to this one:\n\nclientWidth\nclientHeight\noffsetWidth\noffsetHeight\n\n<div bind:offsetWidth={width} bind:offsetHeight={height}>\n    <Chart {width} {height} />\n</div>","rank":null},{"breadcrumbs":["Element directives","bind:group"],"href":"/docs/element-directives#bind-group","content":"<!--- copy: false --->\nbind:group={variable}Inputs that work together can use bind:group.\n\n<!--- file: App.svelte --->\n<script>\n    let tortilla = 'Plain';\n\n    /** @type {Array<string>} */\n    let fillings = [];\n</script>\n\n<!-- grouped radio inputs are mutually exclusive -->\n<input type=\"radio\" bind:group={tortilla} value=\"Plain\" />\n<input type=\"radio\" bind:group={tortilla} value=\"Whole wheat\" />\n<input type=\"radio\" bind:group={tortilla} value=\"Spinach\" />\n\n<!-- grouped checkbox inputs populate an array -->\n<input type=\"checkbox\" bind:group={fillings} value=\"Rice\" />\n<input type=\"checkbox\" bind:group={fillings} value=\"Beans\" />\n<input type=\"checkbox\" bind:group={fillings} value=\"Cheese\" />\n<input type=\"checkbox\" bind:group={fillings} value=\"Guac (extra)\" />bind:group only works if the inputs are in the same Svelte component.","rank":null},{"breadcrumbs":["Element directives","bind:this"],"href":"/docs/element-directives#bind-this","content":"<!--- copy: false --->\nbind:this={dom_node}To get a reference to a DOM node, use bind:this.\n\n<!--- file: App.svelte --->\n<script>\n    import { onMount } from 'svelte';\n\n    /** @type {HTMLCanvasElement} */\n    let canvasElement;\n\n    onMount(() => {\n        const ctx = canvasElement.getContext('2d');\n        drawStuff(ctx);\n    });\n</script>\n\n<canvas bind:this={canvasElement} />","rank":null},{"breadcrumbs":["Element directives","class:name"],"href":"/docs/element-directives#class-name","content":"<!--- copy: false --->\nclass:name={value}<!--- copy: false --->\nclass:nameA class: directive provides a shorter way of toggling a class on an element.\n\n<!-- These are equivalent -->\n<div class={isActive ? 'active' : ''}>...</div>\n<div class:active={isActive}>...</div>\n\n<!-- Shorthand, for when name and value match -->\n<div class:active>...</div>\n\n<!-- Multiple class toggles can be included -->\n<div class:active class:inactive={!active} class:isAdmin>...</div>","rank":null},{"breadcrumbs":["Element directives","style:property"],"href":"/docs/element-directives#style-property","content":"style:property={value}style:property=\"value\"style:propertyThe style: directive provides a shorthand for setting multiple styles on an element.\n\n<!-- These are equivalent -->\n<div style:color=\"red\">...</div>\n<div style=\"color: red;\">...</div>\n\n<!-- Variables can be used -->\n<div style:color={myColor}>...</div>\n\n<!-- Shorthand, for when property and variable name match -->\n<div style:color>...</div>\n\n<!-- Multiple styles can be included -->\n<div style:color style:width=\"12rem\" style:background-color={darkMode ? 'black' : 'white'}>...</div>\n\n<!-- Styles can be marked as important -->\n<div style:color|important=\"red\">...</div>When style: directives are combined with style attributes, the directives will take precedence:\n\n<div style=\"color: blue;\" style:color=\"red\">This will be red</div>","rank":null},{"breadcrumbs":["Element directives","use:action"],"href":"/docs/element-directives#use-action","content":"<!--- copy: false --->\nuse:action<!--- copy: false --->\nuse:action={parameters}/// copy: false\n// @noErrors\naction = (node: HTMLElement, parameters: any) => {\n    update?: (parameters: any) => void,\n    destroy?: () => void\n}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:\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {import('svelte/action').Action}  */\n    function foo(node) {\n        // the node has been mounted in the DOM\n\n        return {\n            destroy() {\n                // the node has been removed from the DOM\n            }\n        };\n    }\n</script>\n\n<div use:foo />An action can have a parameter. If the returned value has an update method, it will be called whenever that parameter changes, immediately after Svelte has applied updates to the markup.\n\nDon'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.\n\n\n<!--- file: App.svelte --->\n<script>\n    export let bar;\n\n    /** @type {import('svelte/action').Action}  */\n    function foo(node, bar) {\n        // the node has been mounted in the DOM\n\n        return {\n            update(bar) {\n                // the value of `bar` has changed\n            },\n\n            destroy() {\n                // the node has been removed from the DOM\n            }\n        };\n    }\n</script>\n\n<div use:foo={bar} />Read more in the svelte/action page.","rank":null},{"breadcrumbs":["Element directives","transition:fn"],"href":"/docs/element-directives#transition-fn","content":"<!--- copy: false --->\ntransition:fn<!--- copy: false --->\ntransition:fn={params}<!--- copy: false --->\ntransition:fn|global<!--- copy: false --->\ntransition:fn|global={params}<!--- copy: false --->\ntransition:fn|local<!--- copy: false --->\ntransition:fn|local={params}/// copy: false\n// @noErrors\ntransition = (node: HTMLElement, params: any, options: { direction: 'in' | 'out' | 'both' }) => {\n    delay?: number,\n    duration?: number,\n    easing?: (t: number) => number,\n    css?: (t: number, u: number) => string,\n    tick?: (t: number, u: number) => void\n}A transition is triggered by an element entering or leaving the DOM as a result of a state change.\n\nWhen 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 been completed.\n\nThe transition: directive indicates a bidirectional transition, which means it can be smoothly reversed while the transition is in progress.\n\n{#if visible}\n    <div transition:fade>fades in and out</div>\n{/if}Transitions are local by default (in Svelte 3, they were global by default). Local transitions only play when the block they belong to is created or destroyed, not when parent blocks are created or destroyed.\n\n{#if x}\n    {#if y}\n        <!-- Svelte 3: <p transition:fade|local> -->\n        <p transition:fade>fades in and out only when y changes</p>\n\n        <!-- Svelte 3: <p transition:fade> -->\n        <p transition:fade|global>fades in and out when x or y change</p>\n    {/if}\n{/if}By default intro transitions will not play on first render. You can modify this behaviour by setting intro: true when you create a component and marking the transition as global.","rank":null},{"breadcrumbs":["Element directives","Transition parameters"],"href":"/docs/element-directives#transition-parameters","content":"Like actions, transitions can have parameters.\n\n(The double {{curlies}} aren't a special syntax; this is an object literal inside an expression tag.)\n\n{#if visible}\n    <div transition:fade={{ duration: 2000 }}>fades in and out over two seconds</div>\n{/if}","rank":null},{"breadcrumbs":["Element directives","Custom transition functions"],"href":"/docs/element-directives#custom-transition-functions","content":"Transitions can use custom functions. If the returned object has a css function, Svelte will create a CSS animation that plays on the element.\n\nThe t argument passed to css is a value between 0 and 1 after the easing function has been applied. In transitions run from 0 to 1, out transitions run from 1 to 0 — in other words, 1 is the element's natural state, as though no transition had been applied. The u argument is equal to 1 - t.\n\nThe function is called repeatedly before the transition begins, with different t and u arguments.\n\n<!--- file: App.svelte --->\n<script>\n    import { elasticOut } from 'svelte/easing';\n\n    /** @type {boolean} */\n    export let visible;\n\n    /**\n     * @param {HTMLElement} node\n     * @param {{ delay?: number, duration?: number, easing?: (t: number) => number }} params\n     */\n    function whoosh(node, params) {\n        const existingTransform = getComputedStyle(node).transform.replace('none', '');\n\n        return {\n            delay: params.delay || 0,\n            duration: params.duration || 400,\n            easing: params.easing || elasticOut,\n            css: (t, u) => `transform: ${existingTransform} scale(${t})`\n        };\n    }\n</script>\n\n{#if visible}\n    <div in:whoosh>whooshes in</div>\n{/if}A custom transition function can also return a tick function, which is called during the transition with the same t and u arguments.\n\nIf it's possible to use css instead of tick, do so — CSS animations can run off the main thread, preventing jank on slower devices.\n\n\n<!--- file: App.svelte --->\n<script>\n    export let visible = false;\n\n    /**\n     * @param {HTMLElement} node\n     * @param {{ speed?: number }} params\n     */\n    function typewriter(node, { speed = 1 }) {\n        const valid = node.childNodes.length === 1 && node.childNodes[0].nodeType === Node.TEXT_NODE;\n\n        if (!valid) {\n            throw new Error(`This transition only works on elements with a single text node child`);\n        }\n\n        const text = node.textContent;\n        const duration = text.length / (speed * 0.01);\n\n        return {\n            duration,\n            tick: (t) => {\n                const i = ~~(text.length * t);\n                node.textContent = text.slice(0, i);\n            }\n        };\n    }\n</script>\n\n{#if visible}\n    <p in:typewriter={{ speed: 1 }}>The quick brown fox jumps over the lazy dog</p>\n{/if}If a transition returns a function instead of a transition object, the function will be called in the next microtask. This allows multiple transitions to coordinate, making crossfade effects possible.\n\nTransition functions also receive a third argument, options, which contains information about the transition.\n\nAvailable values in the options object are:\n\ndirection - one of in, out, or both depending on the type of transition","rank":null},{"breadcrumbs":["Element directives","Transition events"],"href":"/docs/element-directives#transition-events","content":"An element with transitions will dispatch the following events in addition to any standard DOM events:\n\nintrostart\nintroend\noutrostart\noutroend\n\n{#if visible}\n    <p\n        transition:fly={{ y: 200, duration: 2000 }}\n        on:introstart={() => (status = 'intro started')}\n        on:outrostart={() => (status = 'outro started')}\n        on:introend={() => (status = 'intro ended')}\n        on:outroend={() => (status = 'outro ended')}\n    >\n        Flies in and out\n    </p>\n{/if}","rank":null},{"breadcrumbs":["Element directives","in:fn/out:fn"],"href":"/docs/element-directives#in-fn-out-fn","content":"<!--- copy: false --->\nin:fn<!--- copy: false --->\nin:fn={params}<!--- copy: false --->\nin:fn|global<!--- copy: false --->\nin:fn|global={params}<!--- copy: false --->\nin:fn|local<!--- copy: false --->\nin:fn|local={params}<!--- copy: false --->\nout:fn<!--- copy: false --->\nout:fn={params}<!--- copy: false --->\nout:fn|global<!--- copy: false --->\nout:fn|global={params}<!--- copy: false --->\nout:fn|local<!--- copy: false --->\nout:fn|local={params}Similar to transition:, but only applies to elements entering (in:) or leaving (out:) the DOM.\n\nUnlike 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.\n\n{#if visible}\n    <div in:fly out:fade>flies in, fades out</div>\n{/if}","rank":null},{"breadcrumbs":["Element directives","animate:fn"],"href":"/docs/element-directives#animate-fn","content":"<!--- copy: false --->\nanimate:name<!--- copy: false --->\nanimate:name={params}/// copy: false\n// @noErrors\nanimation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {\n    delay?: number,\n    duration?: number,\n    easing?: (t: number) => number,\n    css?: (t: number, u: number) => string,\n    tick?: (t: number, u: number) => void\n}/// copy: false\n// @noErrors\nDOMRect {\n    bottom: number,\n    height: number,\n    ​​left: number,\n    right: number,\n    ​top: number,\n    width: number,\n    x: number,\n    y: number\n}An animation is triggered when the contents of a keyed each block are re-ordered. Animations do not run when an element is added or removed, only when the index of an existing data item within the each block changes. Animate directives must be on an element that is an immediate child of a keyed each block.\n\nAnimations can be used with Svelte's built-in animation functions or custom animation functions.\n\n<!-- When `list` is reordered the animation will run-->\n{#each list as item, index (item)}\n    <li animate:flip>{item}</li>\n{/each}","rank":null},{"breadcrumbs":["Element directives","Animation Parameters"],"href":"/docs/element-directives#animation-parameters","content":"As with actions and transitions, animations can have parameters.\n\n(The double {{curlies}} aren't a special syntax; this is an object literal inside an expression tag.)\n\n{#each list as item, index (item)}\n    <li animate:flip={{ delay: 500 }}>{item}</li>\n{/each}","rank":null},{"breadcrumbs":["Element directives","Custom animation functions"],"href":"/docs/element-directives#custom-animation-functions","content":"Animations can use custom functions that provide the node, an animation object and any parameters as arguments. The animation parameter is an object containing from and to properties each containing a DOMRect describing the geometry of the element in its start and end positions. The from property is the DOMRect of the element in its starting position, and the to property is the DOMRect of the element in its final position after the list has been reordered and the DOM updated.\n\nIf the returned object has a css method, Svelte will create a CSS animation that plays on the element.\n\nThe t argument passed to css is a value that goes from 0 and 1 after the easing function has been applied. The u argument is equal to 1 - t.\n\nThe function is called repeatedly before the animation begins, with different t and u arguments.\n\n\n<script>\n    import { cubicOut } from 'svelte/easing';\n\n    /**\n     * @param {HTMLElement} node\n     * @param {{ from: DOMRect; to: DOMRect }} states\n     * @param {any} params\n     */\n    function whizz(node, { from, to }, params) {\n        const dx = from.left - to.left;\n        const dy = from.top - to.top;\n\n        const d = Math.sqrt(dx * dx + dy * dy);\n\n        return {\n            delay: 0,\n            duration: Math.sqrt(d) * 120,\n            easing: cubicOut,\n            css: (t, u) => `transform: translate(${u * dx}px, ${u * dy}px) rotate(${t * 360}deg);`\n        };\n    }\n</script>\n\n{#each list as item, index (item)}\n    <div animate:whizz>{item}</div>\n{/each}A custom animation function can also return a tick function, which is called during the animation with the same t and u arguments.\n\nIf it's possible to use css instead of tick, do so — CSS animations can run off the main thread, preventing jank on slower devices.\n\n\n<script>\n    import { cubicOut } from 'svelte/easing';\n\n    /**\n     * @param {HTMLElement} node\n     * @param {{ from: DOMRect; to: DOMRect }} states\n     * @param {any} params\n     */\n    function whizz(node, { from, to }, params) {\n        const dx = from.left - to.left;\n        const dy = from.top - to.top;\n\n        const d = Math.sqrt(dx * dx + dy * dy);\n\n        return {\n            delay: 0,\n            duration: Math.sqrt(d) * 120,\n            easing: cubicOut,\n            tick: (t, u) => Object.assign(node.style, { color: t > 0.5 ? 'Pink' : 'Blue' })\n        };\n    }\n</script>\n\n{#each list as item, index (item)}\n    <div animate:whizz>{item}</div>\n{/each}","rank":null},{"breadcrumbs":["Component directives"],"href":"/docs/component-directives","content":"","rank":null},{"breadcrumbs":["Component directives","on:eventname"],"href":"/docs/component-directives#on-eventname","content":"<!--- copy: false --->\non:eventname={handler}Components can emit events using createEventDispatcher or by forwarding DOM events.\n\n<script>\n    import { createEventDispatcher } from 'svelte';\n\n    const dispatch = createEventDispatcher();\n</script>\n\n<!-- programmatic dispatching -->\n<button on:click={() => dispatch('hello')}> one </button>\n\n<!-- declarative event forwarding -->\n<button on:click> two </button>Listening for component events looks the same as listening for DOM events:\n\n<SomeComponent on:whatever={handler} />As with DOM events, if the on: directive is used without a value, the event will be forwarded, meaning that a consumer can listen for it.\n\n<SomeComponent on:whatever />","rank":null},{"breadcrumbs":["Component directives","--style-props"],"href":"/docs/component-directives#style-props","content":"<!--- copy: false --->\n--style-props=\"anycssvalue\"You can also pass styles as props to components for the purposes of theming, using CSS custom properties.\n\nSvelte's implementation is essentially syntactic sugar for adding a wrapper element. This example:\n\n<Slider bind:value min={0} --rail-color=\"black\" --track-color=\"rgb(0, 0, 255)\" />Desugars to this:\n\n<div style=\"display: contents; --rail-color: black; --track-color: rgb(0, 0, 255)\">\n    <Slider bind:value min={0} max={100} />\n</div>Note: Since this is an extra <div>, beware that your CSS structure might accidentally target this. Be mindful of this added wrapper element when using this feature.\n\nFor SVG namespace, the example above desugars into using <g> instead:\n\n<g style=\"--rail-color: black; --track-color: rgb(0, 0, 255)\">\n    <Slider bind:value min={0} max={100} />\n</g>Note: Since this is an extra <g>, beware that your CSS structure might accidentally target this. Be mindful of this added wrapper element when using this feature.\n\nSvelte's CSS Variables support allows for easily themeable components:\n\n<style>\n    .potato-slider-rail {\n        background-color: var(--rail-color, var(--theme-color, 'purple'));\n    }\n</style>So you can set a high-level theme color:\n\n/* global.css */\nhtml {\n    --theme-color: black;\n}Or override it at the consumer level:\n\n<Slider --rail-color=\"goldenrod\" />","rank":null},{"breadcrumbs":["Component directives","bind:property"],"href":"/docs/component-directives#bind-property","content":"bind:property={variable}You can bind to component props using the same syntax as for elements.\n\n<Keypad bind:value={pin} />While Svelte props are reactive without binding, that reactivity only flows downward into the component by default. Using bind:property allows changes to the property from within the component to flow back up out of the component.","rank":null},{"breadcrumbs":["Component directives","bind:this"],"href":"/docs/component-directives#bind-this","content":"<!--- copy: false --->\nbind:this={component_instance}Components also support bind:this, allowing you to interact with component instances programmatically.\n\n<ShoppingCart bind:this={cart} />\n\n<button on:click={() => cart.empty()}> Empty shopping cart </button>Note that we can't do {cart.empty} since cart is undefined when the button is first rendered and throws an error.","rank":null},{"breadcrumbs":["Special elements"],"href":"/docs/special-elements","content":"","rank":null},{"breadcrumbs":["Special elements","<slot>"],"href":"/docs/special-elements#slot","content":"<slot><!-- optional fallback --></slot><slot name=\"x\"><!-- optional fallback --></slot><slot prop={value} />Components can have child content, in the same way that elements can.\n\nThe content is exposed in the child component using the <slot> element, which can contain fallback content that is rendered if no children are provided.\n\n<!-- Widget.svelte -->\n<div>\n    <slot>\n        this fallback content will be rendered when no content is provided, like in the first example\n    </slot>\n</div>\n\n<!-- App.svelte -->\n<Widget />\n<!-- this component will render the default content -->\n\n<Widget>\n    <p>this is some child content that will overwrite the default slot content</p>\n</Widget>Note: If you want to render regular <slot> element, You can use <svelte:element this=&quot;slot&quot; />.","rank":null},{"breadcrumbs":["Special elements","<slot>","<slot name=\"name\">"],"href":"/docs/special-elements#slot-slot-name-name","content":"Named slots allow consumers to target specific areas. They can also have fallback content.\n\n<!-- Widget.svelte -->\n<div>\n    <slot name=\"header\">No header was provided</slot>\n    <p>Some content between header and footer</p>\n    <slot name=\"footer\" />\n</div>\n\n<!-- App.svelte -->\n<Widget>\n    <h1 slot=\"header\">Hello</h1>\n    <p slot=\"footer\">Copyright (c) 2019 Svelte Industries</p>\n</Widget>Components can be placed in a named slot using the syntax <Component slot=&quot;name&quot; />.\nIn order to place content in a slot without using a wrapper element, you can use the special element <svelte:fragment>.\n\n<!-- Widget.svelte -->\n<div>\n    <slot name=\"header\">No header was provided</slot>\n    <p>Some content between header and footer</p>\n    <slot name=\"footer\" />\n</div>\n\n<!-- App.svelte -->\n<Widget>\n    <HeaderComponent slot=\"header\" />\n    <svelte:fragment slot=\"footer\">\n        <p>All rights reserved.</p>\n        <p>Copyright (c) 2019 Svelte Industries</p>\n    </svelte:fragment>\n</Widget>","rank":null},{"breadcrumbs":["Special elements","<slot>","$$slots"],"href":"/docs/special-elements#slot-$$slots","content":"$$slots is an object whose keys are the names of the slots passed into the component by the parent. If the parent does not pass in a slot with a particular name, that name will not be present in $$slots. This allows components to render a slot (and other elements, like wrappers for styling) only if the parent provides it.\n\nNote that explicitly passing in an empty named slot will add that slot's name to $$slots. For example, if a parent passes <div slot=&quot;title&quot; /> to a child component, $$slots.title will be truthy within the child.\n\n<!-- Card.svelte -->\n<div>\n    <slot name=\"title\" />\n    {#if $$slots.description}\n        <!-- This <hr> and slot will render only if a slot named \"description\" is provided. -->\n        <hr />\n        <slot name=\"description\" />\n    {/if}\n</div>\n\n<!-- App.svelte -->\n<Card>\n    <h1 slot=\"title\">Blog Post Title</h1>\n    <!-- No slot named \"description\" was provided so the optional slot will not be rendered. -->\n</Card>","rank":null},{"breadcrumbs":["Special elements","<slot>","<slot key={value}>"],"href":"/docs/special-elements#slot-slot-key-value","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.\n\nThe usual shorthand rules apply — let:item is equivalent to let:item={item}, and <slot {item}> is equivalent to <slot item={item}>.\n\n<!-- FancyList.svelte -->\n<ul>\n    {#each items as item}\n        <li class=\"fancy\">\n            <slot prop={item} />\n        </li>\n    {/each}\n</ul>\n\n<!-- App.svelte -->\n<FancyList {items} let:prop={thing}>\n    <div>{thing.text}</div>\n</FancyList>Named slots can also expose values. The let: directive goes on the element with the slot attribute.\n\n<!-- FancyList.svelte -->\n<ul>\n    {#each items as item}\n        <li class=\"fancy\">\n            <slot name=\"item\" {item} />\n        </li>\n    {/each}\n</ul>\n\n<slot name=\"footer\" />\n\n<!-- App.svelte -->\n<FancyList {items}>\n    <div slot=\"item\" let:item>{item.text}</div>\n    <p slot=\"footer\">Copyright (c) 2019 Svelte Industries</p>\n</FancyList>","rank":null},{"breadcrumbs":["Special elements","<svelte:self>"],"href":"/docs/special-elements#svelte-self","content":"The <svelte:self> element allows a component to include itself, recursively.\n\nIt 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.\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {number} */\n    export let count;\n</script>\n\n{#if count > 0}\n    <p>counting down... {count}</p>\n    <svelte:self count={count - 1} />\n{:else}\n    <p>lift-off!</p>\n{/if}","rank":null},{"breadcrumbs":["Special elements","<svelte:component>"],"href":"/docs/special-elements#svelte-component","content":"<svelte:component this={expression} />The <svelte:component> element renders a component dynamically, using the component constructor specified as the this property. When the property changes, the component is destroyed and recreated.\n\nIf this is falsy, no component is rendered.\n\n<svelte:component this={currentSelection.component} foo={bar} />","rank":null},{"breadcrumbs":["Special elements","<svelte:element>"],"href":"/docs/special-elements#svelte-element","content":"<svelte:element this={expression} />The <svelte:element> element lets you render an element of a dynamically specified type. This is useful for example when displaying rich text content from a CMS. Any properties and event listeners present will be applied to the element.\n\nThe only supported binding is bind:this, since the element type-specific bindings that Svelte does at build time (e.g. bind:value for input elements) do not work with a dynamic tag type.\n\nIf this has a nullish value, the element and its children will not be rendered.\n\nIf this is the name of a void element (e.g., br) and <svelte:element> has child elements, a runtime error will be thrown in development mode.\n\n<script>\n    let tag = 'div';\n\n    export let handler;\n</script>\n\n<svelte:element this={tag} on:click={handler}>Foo</svelte:element>","rank":null},{"breadcrumbs":["Special elements","<svelte:window>"],"href":"/docs/special-elements#svelte-window","content":"<svelte:window on:event={handler} /><svelte:window bind:prop={value} />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.\n\nUnlike <svelte:self>, this element may only appear at the top level of your component and must never be inside a block or element.\n\n<!--- file: App.svelte --->\n<script>\n    /** @param {KeyboardEvent} event */\n    function handleKeydown(event) {\n        alert(`pressed the ${event.key} key`);\n    }\n</script>\n\n<svelte:window on:keydown={handleKeydown} />You can also bind to the following properties:\n\ninnerWidth\ninnerHeight\nouterWidth\nouterHeight\nscrollX\nscrollY\nonline — an alias for window.navigator.onLine\ndevicePixelRatio\n\nAll except scrollX and scrollY are readonly.\n\n<svelte:window bind:scrollY={y} />Note that the page will not be scrolled to the initial value to avoid accessibility issues. Only subsequent changes to the bound variable of scrollX and scrollY will cause scrolling. However, if the scrolling behaviour is desired, call scrollTo() in onMount().","rank":null},{"breadcrumbs":["Special elements","<svelte:document>"],"href":"/docs/special-elements#svelte-document","content":"<svelte:document on:event={handler} /><svelte:document bind:prop={value} />Similarly to <svelte:window>, this element allows you to add listeners to events on document, such as visibilitychange, which don't fire on window. It also lets you use actions on document.\n\nAs with <svelte:window>, this element may only appear the top level of your component and must never be inside a block or element.\n\n<svelte:document on:visibilitychange={handleVisibilityChange} use:someAction />You can also bind to the following properties:\n\nfullscreenElement\nvisibilityState\n\nAll are readonly.","rank":null},{"breadcrumbs":["Special elements","<svelte:body>"],"href":"/docs/special-elements#svelte-body","content":"<svelte:body on:event={handler} />Similarly to <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. It also lets you use actions on the <body> element.\n\nAs with <svelte:window> and <svelte:document>, this element may only appear the top level of your component and must never be inside a block or element.\n\n<svelte:body on:mouseenter={handleMouseenter} on:mouseleave={handleMouseleave} use:someAction />","rank":null},{"breadcrumbs":["Special elements","<svelte:head>"],"href":"/docs/special-elements#svelte-head","content":"<svelte:head>...</svelte:head>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.\n\nAs with <svelte:window>, <svelte:document> and <svelte:body>, this element may only appear at the top level of your component and must never be inside a block or element.\n\n<svelte:head>\n    <title>Hello world!</title>\n    <meta name=\"description\" content=\"This is where the description goes for SEO\" />\n</svelte:head>","rank":null},{"breadcrumbs":["Special elements","<svelte:options>"],"href":"/docs/special-elements#svelte-options","content":"<svelte:options option={value} />The <svelte:options> element provides a place to specify per-component compiler options, which are detailed in the compiler section. The possible options are:\n\nimmutable={true} — you never use mutable data, so the compiler can do simple referential equality checks to determine if values have changed\nimmutable={false} — the default. Svelte will be more conservative about whether or not mutable objects have changed\naccessors={true} — adds getters and setters for the component's props\naccessors={false} — the default\nnamespace=&quot;...&quot; — the namespace where this component will be used, most commonly &quot;svg&quot;; use the &quot;foreign&quot; namespace to opt out of case-insensitive attribute names and HTML-specific warnings\ncustomElement=&quot;...&quot; — the name to use when compiling this component as a custom element\n\n<svelte:options customElement=\"my-custom-element\" />","rank":null},{"breadcrumbs":["Special elements","<svelte:fragment>"],"href":"/docs/special-elements#svelte-fragment","content":"The <svelte:fragment> element allows you to place content in a named slot without wrapping it in a container DOM element. This keeps the flow layout of your document intact.\n\n<!-- Widget.svelte -->\n<div>\n    <slot name=\"header\">No header was provided</slot>\n    <p>Some content between header and footer</p>\n    <slot name=\"footer\" />\n</div>\n\n<!-- App.svelte -->\n<Widget>\n    <h1 slot=\"header\">Hello</h1>\n    <svelte:fragment slot=\"footer\">\n        <p>All rights reserved.</p>\n        <p>Copyright (c) 2019 Svelte Industries</p>\n    </svelte:fragment>\n</Widget>","rank":null},{"breadcrumbs":["svelte"],"href":"/docs/svelte","content":"The svelte package exposes lifecycle functions and the context API.","rank":null},{"breadcrumbs":["svelte","onMount"],"href":"/docs/svelte#onmount","content":"function onMount<T>(\n    fn: () =>\n        | NotFunction<T>\n        | Promise<NotFunction<T>>\n        | (() => any)\n): void;\nThe onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live inside the component; it can be called from an external module).\n\nonMount does not run inside a server-side component.\n\n<script>\n    import { onMount } from 'svelte';\n\n    onMount(() => {\n        console.log('the component has mounted');\n    });\n</script>If a function is returned from onMount, it will be called when the component is unmounted.\n\n<script>\n    import { onMount } from 'svelte';\n\n    onMount(() => {\n        const interval = setInterval(() => {\n            console.log('beep');\n        }, 1000);\n\n        return () => clearInterval(interval);\n    });\n</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.","rank":null},{"breadcrumbs":["svelte","beforeUpdate"],"href":"/docs/svelte#beforeupdate","content":"function beforeUpdate(fn: () => any): void;\nSchedules a callback to run immediately before the component is updated after any state change.\n\nThe first time the callback runs will be before the initial onMount\n\n\n<script>\n    import { beforeUpdate } from 'svelte';\n\n    beforeUpdate(() => {\n        console.log('the component is about to update');\n    });\n</script>","rank":null},{"breadcrumbs":["svelte","afterUpdate"],"href":"/docs/svelte#afterupdate","content":"function afterUpdate(fn: () => any): void;\nSchedules a callback to run immediately after the component has been updated.\n\nThe first time the callback runs will be after the initial onMount\n\n\n<script>\n    import { afterUpdate } from 'svelte';\n\n    afterUpdate(() => {\n        console.log('the component just updated');\n    });\n</script>","rank":null},{"breadcrumbs":["svelte","onDestroy"],"href":"/docs/svelte#ondestroy","content":"function onDestroy(fn: () => any): void;\nSchedules a callback to run immediately before the component is unmounted.\n\nOut of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.\n\n<script>\n    import { onDestroy } from 'svelte';\n\n    onDestroy(() => {\n        console.log('the component is being destroyed');\n    });\n</script>","rank":null},{"breadcrumbs":["svelte","tick"],"href":"/docs/svelte#tick","content":"function tick(): Promise<void>;\nReturns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.\n\n<script>\n    import { beforeUpdate, tick } from 'svelte';\n\n    beforeUpdate(async () => {\n        console.log('the component is about to update');\n        await tick();\n        console.log('the component just updated');\n    });\n</script>","rank":null},{"breadcrumbs":["svelte","setContext"],"href":"/docs/svelte#setcontext","content":"function setContext<T>(key: any, context: T): T;\nAssociates an arbitrary context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.\n\nLike lifecycle functions, this must be called during component initialisation.\n\n<script>\n    import { setContext } from 'svelte';\n\n    setContext('answer', 42);\n</script>Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.","rank":null},{"breadcrumbs":["svelte","getContext"],"href":"/docs/svelte#getcontext","content":"function getContext<T>(key: any): T;\nRetrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.\n\n<script>\n    import { getContext } from 'svelte';\n\n    const answer = getContext('answer');\n</script>","rank":null},{"breadcrumbs":["svelte","hasContext"],"href":"/docs/svelte#hascontext","content":"function hasContext(key: any): boolean;\nChecks whether a given key has been set in the context of a parent component. Must be called during component initialisation.\n\n<script>\n    import { hasContext } from 'svelte';\n\n    if (hasContext('answer')) {\n        // do something\n    }\n</script>","rank":null},{"breadcrumbs":["svelte","getAllContexts"],"href":"/docs/svelte#getallcontexts","content":"function getAllContexts<\n    T extends Map<any, any> = Map<any, any>\n>(): T;\nRetrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.\n\n<script>\n    import { getAllContexts } from 'svelte';\n\n    const contexts = getAllContexts();\n</script>","rank":null},{"breadcrumbs":["svelte","createEventDispatcher"],"href":"/docs/svelte#createeventdispatcher","content":"function createEventDispatcher<\n    EventMap extends Record<string, any> = any\n>(): EventDispatcher<EventMap>;\nCreates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.\n\nComponent events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.\n\n<script>\n    import { createEventDispatcher } from 'svelte';\n\n    const dispatch = createEventDispatcher();\n</script>\n\n<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>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.\n\n<script>\n    function callbackFunction(event) {\n        console.log(`Notify fired! Detail: ${event.detail}`);\n    }\n</script>\n\n<Child on:notify={callbackFunction} />Events can be cancelable by passing a third parameter to the dispatch function. The function returns false if the event is cancelled with event.preventDefault(), otherwise it returns true.\n\n<script>\n    import { createEventDispatcher } from 'svelte';\n\n    const dispatch = createEventDispatcher();\n\n    function notify() {\n        const shouldContinue = dispatch('notify', 'detail value', { cancelable: true });\n        if (shouldContinue) {\n            // no one called preventDefault\n        } else {\n            // a listener called preventDefault\n        }\n    }\n</script>You can type the event dispatcher to define which events it can receive. This will make your code more type safe both within the component (wrong calls are flagged) and when using the component (types of the events are now narrowed). See here how to do it.","rank":null},{"breadcrumbs":["svelte","Types"],"href":"/docs/svelte#types","content":"","rank":null},{"breadcrumbs":["svelte","Types","ComponentConstructorOptions"],"href":"/docs/svelte#types-componentconstructoroptions","content":"interface ComponentConstructorOptions<\n    Props extends Record<string, any> = Record<string, any>\n> {/*…*/}\ntarget: Element | Document | ShadowRoot;\n\n\nanchor?: Element;\n\n\nprops?: Props;\n\n\ncontext?: Map<any, any>;\n\n\nhydrate?: boolean;\n\n\nintro?: boolean;\n\n\n$$inline?: boolean;","rank":null},{"breadcrumbs":["svelte","Types","ComponentEvents"],"href":"/docs/svelte#types-componentevents","content":"Convenience type to get the events the given component expects. Example:\n\n<script lang=\"ts\">\n   import type { ComponentEvents } from 'svelte';\n   import Component from './Component.svelte';\n\n   function handleCloseEvent(event: ComponentEvents<Component>['close']) {\n      console.log(event.detail);\n   }\n</script>\n\n<Component on:close={handleCloseEvent} />\ntype ComponentEvents<Component extends SvelteComponent_1> =\n    Component extends SvelteComponent<any, infer Events>\n        ? Events\n        : never;","rank":null},{"breadcrumbs":["svelte","Types","ComponentProps"],"href":"/docs/svelte#types-componentprops","content":"Convenience type to get the props the given component expects. Example:\n\n<script lang=\"ts\">\n    import type { ComponentProps } from 'svelte';\n    import Component from './Component.svelte';\n\n    const props: ComponentProps<Component> = { foo: 'bar' }; // Errors if these aren't the correct props\n</script>\ntype ComponentProps<Component extends SvelteComponent_1> =\n    Component extends SvelteComponent<infer Props>\n        ? Props\n        : never;","rank":null},{"breadcrumbs":["svelte","Types","ComponentType"],"href":"/docs/svelte#types-componenttype","content":"Convenience type to get the type of a Svelte component. Useful for example in combination with\ndynamic components using <svelte:component>.\n\nExample:\n\n<script lang=\"ts\">\n    import type { ComponentType, SvelteComponent } from 'svelte';\n    import Component1 from './Component1.svelte';\n    import Component2 from './Component2.svelte';\n\n    const component: ComponentType = someLogic() ? Component1 : Component2;\n    const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;\n</script>\n\n<svelte:component this={component} />\n<svelte:component this={componentOfCertainSubType} needsThisProp=\"hello\" />\ntype ComponentType<\n    Component extends SvelteComponent = SvelteComponent\n> = (new (\n    options: ComponentConstructorOptions<\n        Component extends SvelteComponent<infer Props>\n            ? Props\n            : Record<string, any>\n    >\n) => Component) & {\n    /** The custom element version of the component. Only present if compiled with the `customElement` compiler option */\n    element?: typeof HTMLElement;\n};","rank":null},{"breadcrumbs":["svelte","Types","SvelteComponent"],"href":"/docs/svelte#types-sveltecomponent","content":"Base class for Svelte components with some minor dev-enhancements. Used when dev=true.\n\nCan be used to create strongly typed Svelte components.","rank":null},{"breadcrumbs":["svelte","Types","Example:"],"href":"/docs/svelte#types-example","content":"You have component library on npm called component-library, from which\nyou export a component called MyComponent. For Svelte+TypeScript users,\nyou want to provide typings. Therefore you create a index.d.ts:\n\nimport { SvelteComponent } from \"svelte\";\nexport class MyComponent extends SvelteComponent<{foo: string}> {}Typing this makes it possible for IDEs like VS Code with the Svelte extension\nto provide intellisense and to use the component like this in a Svelte file\nwith TypeScript:\n\n<script lang=\"ts\">\n    import { MyComponent } from \"component-library\";\n</script>\n<MyComponent foo={'bar'} />\nclass SvelteComponent<\n    Props extends Record<string, any> = any,\n    Events extends Record<string, any> = any,\n    Slots extends Record<string, any> = any\n> extends SvelteComponent_1<Props, Events> {/*…*/}\n[prop: string]: any;\n\n\nconstructor(options: ComponentConstructorOptions<Props>);\n\n\n$capture_state(): void;\n\n\n$inject_state(): void;","rank":null},{"breadcrumbs":["svelte","Types","SvelteComponentTyped"],"href":"/docs/svelte#types-sveltecomponenttyped","content":"class SvelteComponentTyped<\n    Props extends Record<string, any> = any,\n    Events extends Record<string, any> = any,\n    Slots extends Record<string, any> = any\n> extends SvelteComponent<Props, Events, Slots> {}","rank":null},{"breadcrumbs":["svelte/store"],"href":"/docs/svelte-store","content":"The svelte/store module exports functions for creating readable, writable and derived stores.\n\nKeep in mind that you don't have to use these functions to enjoy the reactive $store syntax in your components. Any object that correctly implements .subscribe, unsubscribe, and (optionally) .set is a valid store, and will work both with the special syntax, and with Svelte's built-in derived stores.\n\nThis makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the store contract to see what a correct implementation looks like.","rank":null},{"breadcrumbs":["svelte/store","writable"],"href":"/docs/svelte-store#writable","content":"function writable<T>(\n    value?: T | undefined,\n    start?: StartStopNotifier<T> | undefined\n): Writable<T>;\nFunction that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional set and update methods.\n\nset is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.\n\nupdate is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.\n\n/// file: store.js\nimport { writable } from 'svelte/store';\n\nconst count = writable(0);\n\ncount.subscribe((value) => {\n    console.log(value);\n}); // logs '0'\n\ncount.set(1); // logs '1'\n\ncount.update((n) => n + 1); // logs '2'If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a set function which changes the value of the store, and an update function which works like the update method on the store, taking a callback to calculate the store's new value from its old value. It must return a stop function that is called when the subscriber count goes from one to zero.\n\n/// file: store.js\nimport { writable } from 'svelte/store';\n\nconst count = writable(0, () => {\n    console.log('got a subscriber');\n    return () => console.log('no more subscribers');\n});\n\ncount.set(1); // does nothing\n\nconst unsubscribe = count.subscribe((value) => {\n    console.log(value);\n}); // logs 'got a subscriber', then '1'\n\nunsubscribe(); // logs 'no more subscribers'Note that the value of a writable is lost when it is destroyed, for example when the page is refreshed. However, you can write your own logic to sync the value to for example the localStorage.","rank":null},{"breadcrumbs":["svelte/store","readable"],"href":"/docs/svelte-store#readable","content":"function readable<T>(\n    value?: T | undefined,\n    start?: StartStopNotifier<T> | undefined\n): Readable<T>;\nCreates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to readable is the same as the second argument to writable.\n\nimport { readable } from 'svelte/store';\n\nconst time = readable(new Date(), (set) => {\n    set(new Date());\n\n    const interval = setInterval(() => {\n        set(new Date());\n    }, 1000);\n\n    return () => clearInterval(interval);\n});\n\nconst ticktock = readable('tick', (set, update) => {\n    const interval = setInterval(() => {\n        update((sound) => (sound === 'tick' ? 'tock' : 'tick'));\n    }, 1000);\n\n    return () => clearInterval(interval);\n});","rank":null},{"breadcrumbs":["svelte/store","derived"],"href":"/docs/svelte-store#derived","content":"function derived<S extends Stores, T>(\n    stores: S,\n    fn: (\n        values: StoresValues<S>,\n        set: (value: T) => void,\n        update: (fn: Updater<T>) => void\n    ) => Unsubscriber | void,\n    initial_value?: T | undefined\n): Readable<T>;\n\nfunction derived<S extends Stores, T>(\n    stores: S,\n    fn: (values: StoresValues<S>) => T,\n    initial_value?: T | undefined\n): Readable<T>;\nDerives a store from one or more other stores. The callback runs initially when the first subscriber subscribes and then whenever the store dependencies change.\n\nIn the simplest version, derived takes a single store, and the callback returns a derived value.\n\nimport { derived } from 'svelte/store';\n\nconst doubled = derived(a, ($a) => $a * 2);The callback can set a value asynchronously by accepting a second argument, set, and an optional third argument, update, calling either or both of them when appropriate.\n\nIn this case, you can also pass a third argument to derived — the initial value of the derived store before set or update is first called. If no initial value is specified, the store's initial value will be undefined.\n\nimport { derived } from 'svelte/store';\n\nconst delayed = derived(\n    a,\n    ($a, set) => {\n        setTimeout(() => set($a), 1000);\n    },\n    2000\n);\n\nconst delayedIncrement = derived(a, ($a, set, update) => {\n    set($a);\n    setTimeout(() => update((x) => x + 1), 1000);\n    // every time $a produces a value, this produces two\n    // values, $a immediately and then $a + 1 a second later\n});If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.\n\nimport { derived } from 'svelte/store';\n\nconst tick = derived(\n    frequency,\n    ($frequency, set) => {\n        const interval = setInterval(() => {\n            set(Date.now());\n        }, 1000 / $frequency);\n\n        return () => {\n            clearInterval(interval);\n        };\n    },\n    2000\n);In both cases, an array of arguments can be passed as the first argument instead of a single store.\n\nimport { derived } from 'svelte/store';\n\nconst summed = derived([a, b], ([$a, $b]) => $a + $b);\n\nconst delayed = derived([a, b], ([$a, $b], set) => {\n    setTimeout(() => set($a + $b), 1000);\n});","rank":null},{"breadcrumbs":["svelte/store","readonly"],"href":"/docs/svelte-store#readonly","content":"function readonly<T>(store: Readable<T>): Readable<T>;\nThis simple helper function makes a store readonly. You can still subscribe to the changes from the original one using this new readable store.\n\nimport { readonly, writable } from 'svelte/store';\n\nconst writableStore = writable(1);\nconst readableStore = readonly(writableStore);\n\nreadableStore.subscribe(console.log);\n\nwritableStore.set(2); // console: 2\n// @errors: 2339\nreadableStore.set(2); // ERROR","rank":null},{"breadcrumbs":["svelte/store","get"],"href":"/docs/svelte-store#get","content":"function get<T>(store: Readable<T>): T;\nGenerally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get allows you to do so.\n\nThis works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.\n\n\nimport { get } from 'svelte/store';\n\nconst value = get(store);","rank":null},{"breadcrumbs":["svelte/store","Types"],"href":"/docs/svelte-store#types","content":"","rank":null},{"breadcrumbs":["svelte/store","Types","Readable"],"href":"/docs/svelte-store#types-readable","content":"Readable interface for subscribing.\n\n\ninterface Readable<T> {/*…*/}\nsubscribe(this: void, run: Subscriber<T>, invalidate?: Invalidator<T>): Unsubscriber;\n\nrun subscription callback\ninvalidate cleanup callback\n\n\nSubscribe on value changes.","rank":null},{"breadcrumbs":["svelte/store","Types","StartStopNotifier"],"href":"/docs/svelte-store#types-startstopnotifier","content":"Start and stop notification callbacks.\nThis function is called when the first subscriber subscribes.\n\n\ntype StartStopNotifier<T> = (\n    set: (value: T) => void,\n    update: (fn: Updater<T>) => void\n) => void | (() => void);","rank":null},{"breadcrumbs":["svelte/store","Types","Subscriber"],"href":"/docs/svelte-store#types-subscriber","content":"Callback to inform of a value updates.\n\n\ntype Subscriber<T> = (value: T) => void;","rank":null},{"breadcrumbs":["svelte/store","Types","Unsubscriber"],"href":"/docs/svelte-store#types-unsubscriber","content":"Unsubscribes from value updates.\n\n\ntype Unsubscriber = () => void;","rank":null},{"breadcrumbs":["svelte/store","Types","Updater"],"href":"/docs/svelte-store#types-updater","content":"Callback to update a value.\n\n\ntype Updater<T> = (value: T) => T;","rank":null},{"breadcrumbs":["svelte/store","Types","Writable"],"href":"/docs/svelte-store#types-writable","content":"Writable interface for both updating and subscribing.\n\n\ninterface Writable<T> extends Readable<T> {/*…*/}\nset(this: void, value: T): void;\n\nvalue to set\n\n\nSet value and inform subscribers.\n\n\n\nupdate(this: void, updater: Updater<T>): void;\n\nupdater callback\n\n\nUpdate value using callback and inform subscribers.","rank":null},{"breadcrumbs":["svelte/motion"],"href":"/docs/svelte-motion","content":"The svelte/motion module exports two functions, tweened and spring, for creating writable stores whose values change over time after set and update, rather than immediately.","rank":null},{"breadcrumbs":["svelte/motion","tweened"],"href":"/docs/svelte-motion#tweened","content":"function tweened<T>(\n    value?: T | undefined,\n    defaults?: TweenedOptions<T> | undefined\n): Tweened<T>;\nTweened stores update their values over a fixed duration. The following options are available:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number | function, default 400) — milliseconds the tween lasts\neasing (function, default t => t) — an easing function\ninterpolate (function) — see below\n\nstore.set and store.update can accept a second options argument that will override the options passed in upon instantiation.\n\nBoth functions return a Promise that resolves when the tween completes. If the tween is interrupted, the promise will never resolve.\n\nOut 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).\n\n<script>\n    import { tweened } from 'svelte/motion';\n    import { cubicOut } from 'svelte/easing';\n\n    const size = tweened(1, {\n        duration: 300,\n        easing: cubicOut\n    });\n\n    function handleClick() {\n        // this is equivalent to size.update(n => n + 1)\n        $size += 1;\n    }\n</script>\n\n<button on:click={handleClick} style=\"transform: scale({$size}); transform-origin: 0 0\">\n    embiggen\n</button>If the initial value is undefined or null, the first value change will take effect immediately. This is useful when you have tweened values that are based on props, and don't want any motion when the component first renders.\n\nimport { tweened } from 'svelte/motion';\nimport { cubicOut } from 'svelte/easing';\n\nconst size = tweened(undefined, {\n    duration: 300,\n    easing: cubicOut\n});\n\n$: $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 package to smoothly interpolate between two colours.\n\n<script>\n    import { interpolateLab } from 'd3-interpolate';\n    import { tweened } from 'svelte/motion';\n\n    const colors = ['rgb(255, 62, 0)', 'rgb(64, 179, 255)', 'rgb(103, 103, 120)'];\n\n    const color = tweened(colors[0], {\n        duration: 800,\n        interpolate: interpolateLab\n    });\n</script>\n\n{#each colors as c}\n    <button style=\"background-color: {c}; color: white; border: none;\" on:click={(e) => color.set(c)}>\n        {c}\n    </button>\n{/each}\n\n<h1 style=\"color: {$color}\">{$color}</h1>","rank":null},{"breadcrumbs":["svelte/motion","spring"],"href":"/docs/svelte-motion#spring","content":"function spring<T = any>(\n    value?: T | undefined,\n    opts?: SpringOpts | undefined\n): Spring<T>;\nA spring store gradually changes to its target value based on its stiffness and damping parameters. Whereas tweened stores change their values over a fixed duration, spring stores change over a duration that is determined by their existing velocity, allowing for more natural-seeming motion in many situations. The following options are available:\n\nstiffness (number, default 0.15) — a value between 0 and 1 where higher means a 'tighter' spring\ndamping (number, default 0.8) — a value between 0 and 1 where lower means a 'springier' spring\nprecision (number, default 0.01) — determines the threshold at which the spring is considered to have 'settled', where lower means more precise\n\nAll of the options above can be changed while the spring is in motion, and will take immediate effect.\n\nimport { spring } from 'svelte/motion';\n\nconst size = spring(100);\nsize.stiffness = 0.3;\nsize.damping = 0.4;\nsize.precision = 0.005;As with tweened stores, set and update return a Promise that resolves if the spring settles.\n\nBoth set and update can take a second argument — an object with hard or soft properties. { hard: true } sets the target value immediately; { soft: n } preserves existing momentum for n seconds before settling. { soft: true } is equivalent to { soft: 0.5 }.\n\nimport { spring } from 'svelte/motion';\n\nconst coords = spring({ x: 50, y: 50 });\n// updates the value immediately\ncoords.set({ x: 100, y: 200 }, { hard: true });\n// preserves existing momentum for 1s\ncoords.update(\n    (target_coords, coords) => {\n        return { x: target_coords.x, y: coords.y };\n    },\n    { soft: 1 }\n);See a full example on the spring tutorial.\n\n<script>\n    import { spring } from 'svelte/motion';\n\n    const coords = spring(\n        { x: 50, y: 50 },\n        {\n            stiffness: 0.1,\n            damping: 0.25\n        }\n    );\n</script>If the initial value is undefined or null, the first value change will take effect immediately, just as with tweened values (see above).\n\nimport { spring } from 'svelte/motion';\n\nconst size = spring();\n$: $size = big ? 100 : 10;","rank":null},{"breadcrumbs":["svelte/motion","Types"],"href":"/docs/svelte-motion#types","content":"","rank":null},{"breadcrumbs":["svelte/motion","Types","Spring"],"href":"/docs/svelte-motion#types-spring","content":"interface Spring<T> extends Readable<T> {/*…*/}\nset: (new_value: T, opts?: SpringUpdateOpts) => Promise<void>;\n\n\nupdate: (fn: Updater<T>, opts?: SpringUpdateOpts) => Promise<void>;\n\n\nprecision: number;\n\n\ndamping: number;\n\n\nstiffness: number;","rank":null},{"breadcrumbs":["svelte/motion","Types","Tweened"],"href":"/docs/svelte-motion#types-tweened","content":"interface Tweened<T> extends Readable<T> {/*…*/}\nset(value: T, opts?: TweenedOptions<T>): Promise<void>;\n\n\nupdate(updater: Updater<T>, opts?: TweenedOptions<T>): Promise<void>;","rank":null},{"breadcrumbs":["svelte/transition"],"href":"/docs/svelte-transition","content":"The svelte/transition module exports seven functions: fade, blur, fly, slide, scale, draw and crossfade. They are for use with Svelte transitions.","rank":null},{"breadcrumbs":["svelte/transition","fade"],"href":"/docs/svelte-transition#fade","content":"function fade(\n    node: Element,\n    { delay, duration, easing }?: FadeParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:fade={params}<!--- copy: false --->\nin:fade={params}<!--- copy: false --->\nout:fade={params}Animates the opacity of an element from 0 to the current opacity for in transitions and from the current opacity to 0 for out transitions.\n\nfade accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number, default 400) — milliseconds the transition lasts\neasing (function, default linear) — an easing function\n\nYou can see the fade transition in action in the transition tutorial.\n\n<script>\n    import { fade } from 'svelte/transition';\n</script>\n\n{#if condition}\n    <div transition:fade={{ delay: 250, duration: 300 }}>fades in and out</div>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","blur"],"href":"/docs/svelte-transition#blur","content":"function blur(\n    node: Element,\n    {\n        delay,\n        duration,\n        easing,\n        amount,\n        opacity\n    }?: BlurParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:blur={params}<!--- copy: false --->\nin:blur={params}<!--- copy: false --->\nout:blur={params}Animates a blur filter alongside an element's opacity.\n\nblur accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number, default 400) — milliseconds the transition lasts\neasing (function, default cubicInOut) — an easing function\nopacity (number, default 0) - the opacity value to animate out to and in from\namount (number | string, default 5) - the size of the blur. Supports css units (for example: &quot;4rem&quot;). The default unit is px\n\n<script>\n    import { blur } from 'svelte/transition';\n</script>\n\n{#if condition}\n    <div transition:blur={{ amount: 10 }}>fades in and out</div>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","fly"],"href":"/docs/svelte-transition#fly","content":"function fly(\n    node: Element,\n    {\n        delay,\n        duration,\n        easing,\n        x,\n        y,\n        opacity\n    }?: FlyParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:fly={params}<!--- copy: false --->\nin:fly={params}<!--- copy: false --->\nout:fly={params}Animates the x and y positions and the opacity of an element. in transitions animate from the provided values, passed as parameters to the element's default values. out transitions animate from the element's default values to the provided values.\n\nfly accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number, default 400) — milliseconds the transition lasts\neasing (function, default cubicOut) — an easing function\nx (number | string, default 0) - the x offset to animate out to and in from\ny (number | string, default 0) - the y offset to animate out to and in from\nopacity (number, default 0) - the opacity value to animate out to and in from\n\nx and y use px by default but support css units, for example x: '100vw' or y: '50%'.\nYou can see the fly transition in action in the transition tutorial.\n\n<script>\n    import { fly } from 'svelte/transition';\n    import { quintOut } from 'svelte/easing';\n</script>\n\n{#if condition}\n    <div\n        transition:fly={{ delay: 250, duration: 300, x: 100, y: 500, opacity: 0.5, easing: quintOut }}\n    >\n        flies in and out\n    </div>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","slide"],"href":"/docs/svelte-transition#slide","content":"function slide(\n    node: Element,\n    {\n        delay,\n        duration,\n        easing,\n        axis\n    }?: SlideParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:slide={params}<!--- copy: false --->\nin:slide={params}<!--- copy: false --->\nout:slide={params}Slides an element in and out.\n\nslide accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number, default 400) — milliseconds the transition lasts\neasing (function, default cubicOut) — an easing function\n\naxis (x | y, default y) — the axis of motion along which the transition occurs\n\n<script>\n    import { slide } from 'svelte/transition';\n    import { quintOut } from 'svelte/easing';\n</script>\n\n{#if condition}\n    <div transition:slide={{ delay: 250, duration: 300, easing: quintOut, axis: 'x' }}>\n        slides in and out horizontally\n    </div>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","scale"],"href":"/docs/svelte-transition#scale","content":"function scale(\n    node: Element,\n    {\n        delay,\n        duration,\n        easing,\n        start,\n        opacity\n    }?: ScaleParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:scale={params}<!--- copy: false --->\nin:scale={params}<!--- copy: false --->\nout:scale={params}Animates the opacity and scale of an element. in transitions animate from an element's current (default) values to the provided values, passed as parameters. out transitions animate from the provided values to an element's default values.\n\nscale accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number, default 400) — milliseconds the transition lasts\neasing (function, default cubicOut) — an easing function\nstart (number, default 0) - the scale value to animate out to and in from\nopacity (number, default 0) - the opacity value to animate out to and in from\n\n<script>\n    import { scale } from 'svelte/transition';\n    import { quintOut } from 'svelte/easing';\n</script>\n\n{#if condition}\n    <div transition:scale={{ duration: 500, delay: 500, opacity: 0.5, start: 0.5, easing: quintOut }}>\n        scales in and out\n    </div>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","draw"],"href":"/docs/svelte-transition#draw","content":"function draw(\n    node: SVGElement & {\n        getTotalLength(): number;\n    },\n    {\n        delay,\n        speed,\n        duration,\n        easing\n    }?: DrawParams | undefined\n): TransitionConfig;\n<!--- copy: false --->\ntransition:draw={params}<!--- copy: false --->\nin:draw={params}<!--- copy: false --->\nout:draw={params}Animates the stroke of an SVG element, like a snake in a tube. in transitions begin with the path invisible and draw the path to the screen over time. out transitions start in a visible state and gradually erase the path. draw only works with elements that have a getTotalLength method, like <path> and <polyline>.\n\ndraw accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nspeed (number, default undefined) - the speed of the animation, see below.\nduration (number | function, default 800) — milliseconds the transition lasts\neasing (function, default cubicInOut) — an easing function\n\nThe speed parameter is a means of setting the duration of the transition relative to the path's length. It is a 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.\n\n<script>\n    import { draw } from 'svelte/transition';\n    import { quintOut } from 'svelte/easing';\n</script>\n\n<svg viewBox=\"0 0 5 5\" xmlns=\"http://www.w3.org/2000/svg\">\n    {#if condition}\n        <path\n            transition:draw={{ duration: 5000, delay: 500, easing: quintOut }}\n            d=\"M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z\"\n            fill=\"none\"\n            stroke=\"cornflowerblue\"\n            stroke-width=\"0.1px\"\n            stroke-linejoin=\"round\"\n        />\n    {/if}\n</svg>","rank":null},{"breadcrumbs":["svelte/transition","crossfade"],"href":"/docs/svelte-transition#crossfade","content":"function crossfade({\n    fallback,\n    ...defaults\n}: CrossfadeParams & {\n    fallback?:\n        | ((\n                node: Element,\n                params: CrossfadeParams,\n                intro: boolean\n          ) => TransitionConfig)\n        | undefined;\n}): [\n    (\n        node: any,\n        params: CrossfadeParams & {\n            key: any;\n        }\n    ) => () => TransitionConfig,\n    (\n        node: any,\n        params: CrossfadeParams & {\n            key: any;\n        }\n    ) => () => TransitionConfig\n];\nThe crossfade function creates a pair of transitions called send and receive. When an element is 'sent', it looks for a corresponding element being 'received', and generates a transition that transforms the element to its counterpart's position and fades it out. When an element is 'received', the reverse happens. If there is no counterpart, the fallback transition is used.\n\ncrossfade accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number | function, default 800) — milliseconds the transition lasts\neasing (function, default cubicOut) — an easing function\nfallback (function) — A fallback transition to use for send when there is no matching element being received, and for receive when there is no element being sent.\n\n<script>\n    import { crossfade } from 'svelte/transition';\n    import { quintOut } from 'svelte/easing';\n\n    const [send, receive] = crossfade({\n        duration: 1500,\n        easing: quintOut\n    });\n</script>\n\n{#if condition}\n    <h1 in:send={{ key }} out:receive={{ key }}>BIG ELEM</h1>\n{:else}\n    <small in:send={{ key }} out:receive={{ key }}>small elem</small>\n{/if}","rank":null},{"breadcrumbs":["svelte/transition","Types"],"href":"/docs/svelte-transition#types","content":"","rank":null},{"breadcrumbs":["svelte/transition","Types","BlurParams"],"href":"/docs/svelte-transition#types-blurparams","content":"interface BlurParams {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;\n\n\namount?: number | string;\n\n\nopacity?: number;","rank":null},{"breadcrumbs":["svelte/transition","Types","CrossfadeParams"],"href":"/docs/svelte-transition#types-crossfadeparams","content":"interface CrossfadeParams {/*…*/}\ndelay?: number;\n\n\nduration?: number | ((len: number) => number);\n\n\neasing?: EasingFunction;","rank":null},{"breadcrumbs":["svelte/transition","Types","DrawParams"],"href":"/docs/svelte-transition#types-drawparams","content":"interface DrawParams {/*…*/}\ndelay?: number;\n\n\nspeed?: number;\n\n\nduration?: number | ((len: number) => number);\n\n\neasing?: EasingFunction;","rank":null},{"breadcrumbs":["svelte/transition","Types","EasingFunction"],"href":"/docs/svelte-transition#types-easingfunction","content":"type EasingFunction = (t: number) => number;","rank":null},{"breadcrumbs":["svelte/transition","Types","FadeParams"],"href":"/docs/svelte-transition#types-fadeparams","content":"interface FadeParams {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;","rank":null},{"breadcrumbs":["svelte/transition","Types","FlyParams"],"href":"/docs/svelte-transition#types-flyparams","content":"interface FlyParams {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;\n\n\nx?: number | string;\n\n\ny?: number | string;\n\n\nopacity?: number;","rank":null},{"breadcrumbs":["svelte/transition","Types","ScaleParams"],"href":"/docs/svelte-transition#types-scaleparams","content":"interface ScaleParams {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;\n\n\nstart?: number;\n\n\nopacity?: number;","rank":null},{"breadcrumbs":["svelte/transition","Types","SlideParams"],"href":"/docs/svelte-transition#types-slideparams","content":"interface SlideParams {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;\n\n\naxis?: 'x' | 'y';","rank":null},{"breadcrumbs":["svelte/transition","Types","TransitionConfig"],"href":"/docs/svelte-transition#types-transitionconfig","content":"interface TransitionConfig {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: EasingFunction;\n\n\ncss?: (t: number, u: number) => string;\n\n\ntick?: (t: number, u: number) => void;","rank":null},{"breadcrumbs":["svelte/animate"],"href":"/docs/svelte-animate","content":"The svelte/animate module exports one function for use with Svelte animations.","rank":null},{"breadcrumbs":["svelte/animate","flip"],"href":"/docs/svelte-animate#flip","content":"function flip(\n    node: Element,\n    {\n        from,\n        to\n    }: {\n        from: DOMRect;\n        to: DOMRect;\n    },\n    params?: FlipParams\n): AnimationConfig;\n<!--- copy: false --->\nanimate:flip={params}The flip function calculates the start and end position of an element and animates between them, translating the x and y values. flip stands for First, Last, Invert, Play.\n\nflip accepts the following parameters:\n\ndelay (number, default 0) — milliseconds before starting\nduration (number | function, default d => Math.sqrt(d) * 120) — see below\neasing (function, default cubicOut) — an easing function\n\nduration can be provided as either:\n\na number, in milliseconds.\na function, distance: number => duration: number, receiving the distance the element will travel in pixels and returning the duration in milliseconds. This allows you to assign a duration that is relative to the distance travelled by each element.\n\nYou can see a full example on the animations tutorial.\n\n<script>\n    import { flip } from 'svelte/animate';\n    import { quintOut } from 'svelte/easing';\n\n    let list = [1, 2, 3];\n</script>\n\n{#each list as n (n)}\n    <div animate:flip={{ delay: 250, duration: 250, easing: quintOut }}>\n        {n}\n    </div>\n{/each}","rank":null},{"breadcrumbs":["svelte/animate","Types"],"href":"/docs/svelte-animate#types","content":"","rank":null},{"breadcrumbs":["svelte/animate","Types","AnimationConfig"],"href":"/docs/svelte-animate#types-animationconfig","content":"interface AnimationConfig {/*…*/}\ndelay?: number;\n\n\nduration?: number;\n\n\neasing?: (t: number) => number;\n\n\ncss?: (t: number, u: number) => string;\n\n\ntick?: (t: number, u: number) => void;","rank":null},{"breadcrumbs":["svelte/animate","Types","FlipParams"],"href":"/docs/svelte-animate#types-flipparams","content":"interface FlipParams {/*…*/}\ndelay?: number;\n\n\nduration?: number | ((len: number) => number);\n\n\neasing?: (t: number) => number;","rank":null},{"breadcrumbs":["svelte/easing"],"href":"/docs/svelte-easing","content":"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.\n\nYou can explore the various eases using the ease visualiser in the examples section.\n\nease in out inOut","rank":null},{"breadcrumbs":["svelte/action"],"href":"/docs/svelte-action","content":"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:\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {import('svelte/action').Action}  */\n    function foo(node) {\n        // the node has been mounted in the DOM\n\n        return {\n            destroy() {\n                // the node has been removed from the DOM\n            }\n        };\n    }\n</script>\n\n<div use:foo />An action can have a parameter. If the returned value has an update method, it will be called immediately after Svelte has applied updates to the markup whenever that parameter changes.\n\nDon't worry 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.\n\n\n<!--- file: App.svelte --->\n<script>\n    /** @type {string} */\n    export let bar;\n\n    /** @type {import('svelte/action').Action<HTMLElement, string>}  */\n    function foo(node, bar) {\n        // the node has been mounted in the DOM\n\n        return {\n            update(bar) {\n                // the value of `bar` has changed\n            },\n\n            destroy() {\n                // the node has been removed from the DOM\n            }\n        };\n    }\n</script>\n\n<div use:foo={bar} />","rank":null},{"breadcrumbs":["svelte/action","Attributes"],"href":"/docs/svelte-action#attributes","content":"Sometimes actions emit custom events and apply custom attributes to the element they are applied to. To support this, actions typed with Action or ActionReturn type can have a last parameter, Attributes:\n\n<!--- file: App.svelte --->\n<script>\n    /**\n     * @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>}\n     */\n    function foo(node, { prop }) {\n        // the node has been mounted in the DOM\n\n        //...LOGIC\n        node.dispatchEvent(new CustomEvent('emit', { detail: 'hello' }));\n\n        return {\n            destroy() {\n                // the node has been removed from the DOM\n            }\n        };\n    }\n</script>\n\n<div on:emit={handleEmit} use:foo={{ prop: 'someValue' }} />","rank":null},{"breadcrumbs":["svelte/action","Types"],"href":"/docs/svelte-action#types","content":"","rank":null},{"breadcrumbs":["svelte/action","Types","Action"],"href":"/docs/svelte-action#types-action","content":"Actions are functions that are called when an element is created.\nYou can use this interface to type such actions.\nThe following example defines an action that only works on <div> elements\nand optionally accepts a parameter which it has a default value for:\n\nexport const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {\n  // ...\n}Action<HTMLDivElement> and Action<HTMLDivElement, undefined> both signal that the action accepts no parameters.\n\nYou can return an object with methods update and destroy from the function and type which additional attributes and events it has.\nSee interface ActionReturn for more details.\n\nDocs: https://svelte.dev/docs/svelte-action\n\n\ninterface Action<\n    Element = HTMLElement,\n    Parameter = undefined,\n    Attributes extends Record<string, any> = Record<\n        never,\n        any\n    >\n> {/*…*/}\n<Node extends Element>(\n    ...args: undefined extends Parameter\n        ? [node: Node, parameter?: Parameter]\n        : [node: Node, parameter: Parameter]\n): void | ActionReturn<Parameter, Attributes>;","rank":null},{"breadcrumbs":["svelte/action","Types","ActionReturn"],"href":"/docs/svelte-action#types-actionreturn","content":"Actions can return an object containing the two properties defined in this interface. Both are optional.\n\nupdate: An action can have a parameter. This method will be called whenever that parameter changes,\nimmediately after Svelte has applied updates to the markup. ActionReturn and ActionReturn<undefined> both\nmean that the action accepts no parameters.\ndestroy: Method that is called after the element is unmounted\n\nAdditionally, you can specify which additional attributes and events the action enables on the applied element.\nThis applies to TypeScript typings only and has no effect at runtime.\n\nExample usage:\n\ninterface Attributes {\n    newprop?: string;\n    'on:event': (e: CustomEvent<boolean>) => void;\n}\n\nexport function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {\n    // ...\n    return {\n        update: (updatedParameter) => {...},\n        destroy: () => {...}\n    };\n}Docs: https://svelte.dev/docs/svelte-action\n\n\ninterface ActionReturn<\n    Parameter = undefined,\n    Attributes extends Record<string, any> = Record<\n        never,\n        any\n    >\n> {/*…*/}\nupdate?: (parameter: Parameter) => void;\n\n\ndestroy?: () => void;","rank":null},{"breadcrumbs":["svelte/compiler"],"href":"/docs/svelte-compiler","content":"Typically, you won't interact with the Svelte compiler directly, but will instead integrate it into your build system using a bundler plugin. The bundler plugin that the Svelte team most recommends and invests in is vite-plugin-svelte. The SvelteKit framework provides a setup leveraging vite-plugin-svelte to build applications as well as a tool for packaging Svelte component libraries. Svelte Society maintains a list of other bundler plugins for additional tools like Rollup and Webpack.\n\nNonetheless, it's useful to understand how to use the compiler, since bundler plugins generally expose compiler options to you.","rank":null},{"breadcrumbs":["svelte/compiler","compile"],"href":"/docs/svelte-compiler#compile","content":"function compile(\n    source: string,\n    options?: CompileOptions\n): CompileResult;\nThis is where the magic happens. svelte.compile takes your component source code, and turns it into a JavaScript module that exports a class.\n\nimport { compile } from 'svelte/compiler';\n\nconst result = compile(source, {\n    // options\n});Refer to CompileOptions for all the available options.\n\nThe returned result object contains the code for your component, along with useful bits of metadata.\n\nconst { js, css, ast, warnings, vars, stats } = compile(source);Refer to CompileResult for a full description of the compile result.","rank":null},{"breadcrumbs":["svelte/compiler","parse"],"href":"/docs/svelte-compiler#parse","content":"function parse(\n    template: string,\n    options?: ParserOptions\n): Ast;\nThe parse function parses a component, returning only its abstract syntax tree. Unlike compiling with the generate: false option, this will not perform any validation or other analysis of the component beyond parsing it. Note that the returned AST is not considered public API, so breaking changes could occur at any point in time.\n\nimport { parse } from 'svelte/compiler';\n\nconst ast = parse(source, { filename: 'App.svelte' });","rank":null},{"breadcrumbs":["svelte/compiler","preprocess"],"href":"/docs/svelte-compiler#preprocess","content":"function preprocess(\n    source: string,\n    preprocessor: PreprocessorGroup | PreprocessorGroup[],\n    options?:\n        | {\n                filename?: string | undefined;\n          }\n        | undefined\n): Promise<Processed>;\nA number of official and community-maintained preprocessing plugins are available to allow you to use Svelte with tools like TypeScript, PostCSS, SCSS, and Less.\n\nYou can write your own preprocessor using the svelte.preprocess API.\n\nThe preprocess function provides convenient hooks for arbitrarily transforming component source code. For example, it can be used to convert a <style lang=&quot;sass&quot;> block into vanilla CSS.\n\nThe first argument is the component source code. The second is an array of preprocessors (or a single preprocessor, if you only have one), where a preprocessor is an object with a name which is required, and markup, script and style functions, each of which is optional.\n\nThe markup function receives the entire component source text, along with the component's filename if it was specified in the third argument.\n\nThe script and style functions receive the contents of <script> and <style> elements respectively (content) as well as the entire component source text (markup). In addition to filename, they get an object of the element's attributes.\n\nEach markup, script or style function must return an object (or a Promise that resolves to an object) with a code property, representing the transformed source code. Optionally they can return an array of dependencies which represents files to watch for changes, and a map object which is a sourcemap mapping back the transformation to the original code. script and style preprocessors can optionally return a record of attributes which represent the updated attributes on the script/style tag.\n\nPreprocessor functions should return a map object whenever possible or else debugging becomes harder as stack traces can't link to the original code correctly.\n\n\nimport { preprocess } from 'svelte/compiler';\nimport MagicString from 'magic-string';\n\nconst { code } = await preprocess(\n    source,\n    {\n        markup: ({ content, filename }) => {\n            const pos = content.indexOf('foo');\n            if (pos < 0) {\n                return { code: content };\n            }\n            const s = new MagicString(content, { filename });\n            s.overwrite(pos, pos + 3, 'bar', { storeName: true });\n            return {\n                code: s.toString(),\n                map: s.generateMap()\n            };\n        }\n    },\n    {\n        filename: 'App.svelte'\n    }\n);If a dependencies array is returned, it will be included in the result object. This is used by packages like vite-plugin-svelte and rollup-plugin-svelte to watch additional files for changes, in the case where your <style> tag has an @import (for example).\n\nimport { preprocess } from 'svelte/compiler';\nimport MagicString from 'magic-string';\nimport sass from 'sass';\nimport { dirname } from 'path';\n\nconst { code } = await preprocess(\n    source,\n    {\n        name: 'my-fancy-preprocessor',\n        markup: ({ content, filename }) => {\n            // Return code as is when no foo string present\n            const pos = content.indexOf('foo');\n            if (pos < 0) {\n                return;\n            }\n\n            // Replace foo with bar using MagicString which provides\n            // a source map along with the changed code\n            const s = new MagicString(content, { filename });\n            s.overwrite(pos, pos + 3, 'bar', { storeName: true });\n\n            return {\n                code: s.toString(),\n                map: s.generateMap({ hires: true, file: filename })\n            };\n        },\n        style: async ({ content, attributes, filename }) => {\n            // only process <style lang=\"sass\">\n            if (attributes.lang !== 'sass') return;\n\n            const { css, stats } = await new Promise((resolve, reject) =>\n                sass.render(\n                    {\n                        file: filename,\n                        data: content,\n                        includePaths: [dirname(filename)]\n                    },\n                    (err, result) => {\n                        if (err) reject(err);\n                        else resolve(result);\n                    }\n                )\n            );\n\n            // remove lang attribute from style tag\n            delete attributes.lang;\n\n            return {\n                code: css.toString(),\n                dependencies: stats.includedFiles,\n                attributes\n            };\n        }\n    },\n    {\n        filename: 'App.svelte'\n    }\n);Multiple preprocessors can be used together. The output of the first becomes the input to the second. Within one preprocessor, markup runs first, then script and style.\n\nIn Svelte 3, all markup functions ran first, then all script and then all style preprocessors. This order was changed in Svelte 4.\n\n\nimport { preprocess } from 'svelte/compiler';\n\nconst { code } = await preprocess(source, [\n    {\n        name: 'first preprocessor',\n        markup: () => {\n            console.log('this runs first');\n        },\n        script: () => {\n            console.log('this runs second');\n        },\n        style: () => {\n            console.log('this runs third');\n        }\n    },\n    {\n        name: 'second preprocessor',\n        markup: () => {\n            console.log('this runs fourth');\n        },\n        script: () => {\n            console.log('this runs fifth');\n        },\n        style: () => {\n            console.log('this runs sixth');\n        }\n    }\n], {\n    filename: 'App.svelte'\n});","rank":null},{"breadcrumbs":["svelte/compiler","walk"],"href":"/docs/svelte-compiler#walk","content":"The walk function provides a way to walk the abstract syntax trees generated by the parser, using the compiler's own built-in instance of estree-walker.\n\nThe walker takes an abstract syntax tree to walk and an object with two optional methods: enter and leave. For each node, enter is called (if present). Then, unless this.skip() is called during enter, each of the children are traversed, and then leave is called on the node.\n\nimport { walk } from 'svelte/compiler';\n\nwalk(ast, {\n    enter(node, parent, prop, index) {\n        do_something(node);\n        if (should_skip_children(node)) {\n            this.skip();\n        }\n    },\n    leave(node, parent, prop, index) {\n        do_something_else(node);\n    }\n});","rank":null},{"breadcrumbs":["svelte/compiler","VERSION"],"href":"/docs/svelte-compiler#version","content":"const VERSION: string;\nThe current version, as set in package.json.\n\nimport { VERSION } from 'svelte/compiler';\nconsole.log(`running svelte version ${VERSION}`);","rank":null},{"breadcrumbs":["svelte/compiler","Types"],"href":"/docs/svelte-compiler#types","content":"","rank":null},{"breadcrumbs":["svelte/compiler","Types","CompileOptions"],"href":"/docs/svelte-compiler#types-compileoptions","content":"interface CompileOptions {/*…*/}\nname?: string;\n\n\ndefault\n 'Component'\n\n\nSets the name of the resulting JavaScript class (though the compiler will rename it if it would otherwise conflict with other variables in scope).\nIt will normally be inferred from filename\n\n\n\nfilename?: string;\n\n\ndefault\n null\n\n\nUsed for debugging hints and sourcemaps. Your bundler plugin will set it automatically.\n\n\n\ngenerate?: 'dom' | 'ssr' | false;\n\n\ndefault\n 'dom'\n\n\nIf &quot;dom&quot;, Svelte emits a JavaScript class for mounting to the DOM.\nIf &quot;ssr&quot;, Svelte emits an object with a render method suitable for server-side rendering.\nIf false, no JavaScript or CSS is returned; just metadata.\n\n\n\nerrorMode?: 'throw' | 'warn';\n\n\ndefault\n 'throw'\n\n\nIf &quot;throw&quot;, Svelte throws when a compilation error occurred.\nIf &quot;warn&quot;, Svelte will treat errors as warnings and add them to the warning report.\n\n\n\nvarsReport?: 'full' | 'strict' | false;\n\n\ndefault\n 'strict'\n\n\nIf &quot;strict&quot;, Svelte returns a variables report with only variables that are not globals nor internals.\nIf &quot;full&quot;, Svelte returns a variables report with all detected variables.\nIf false, no variables report is returned.\n\n\n\nsourcemap?: object | string;\n\n\ndefault\n null\n\n\nAn initial sourcemap that will be merged into the final output sourcemap.\nThis is usually the preprocessor sourcemap.\n\n\n\nenableSourcemap?: EnableSourcemap;\n\n\ndefault\n true\n\n\nIf true, Svelte generate sourcemaps for components.\nUse an object with js or css for more granular control of sourcemap generation.\n\n\n\noutputFilename?: string;\n\n\ndefault\n null\n\n\nUsed for your JavaScript sourcemap.\n\n\n\ncssOutputFilename?: string;\n\n\ndefault\n null\n\n\nUsed for your CSS sourcemap.\n\n\n\nsveltePath?: string;\n\n\ndefault\n 'svelte'\n\n\nThe location of the svelte package.\nAny imports from svelte or svelte/[module] will be modified accordingly.\n\n\n\ndev?: boolean;\n\n\ndefault\n false\n\n\nIf true, causes extra code to be added to components that will perform runtime checks and provide debugging information during development.\n\n\n\naccessors?: boolean;\n\n\ndefault\n false\n\n\nIf true, getters and setters will be created for the component's props. If false, they will only be created for readonly exported values (i.e. those declared with const, class and function). If compiling with customElement: true this option defaults to true.\n\n\n\nimmutable?: boolean;\n\n\ndefault\n false\n\n\nIf true, tells the compiler that you promise not to mutate any objects.\nThis allows it to be less conservative about checking whether values have changed.\n\n\n\nhydratable?: boolean;\n\n\ndefault\n false\n\n\nIf true when generating DOM code, enables the hydrate: true runtime option, which allows a component to upgrade existing DOM rather than creating new DOM from scratch.\nWhen generating SSR code, this adds markers to <head> elements so that hydration knows which to replace.\n\n\n\nlegacy?: boolean;\n\n\ndefault\n false\n\n\nIf true, generates code that will work in IE9 and IE10, which don't support things like element.dataset.\n\n\n\ncustomElement?: boolean;\n\n\ndefault\n false\n\n\nIf true, tells the compiler to generate a custom element constructor instead of a regular Svelte component.\n\n\n\ntag?: string;\n\n\ndefault\n null\n\n\nA string that tells Svelte what tag name to register the custom element with.\nIt must be a lowercase alphanumeric string with at least one hyphen, e.g. &quot;my-element&quot;.\n\n\n\ncss?: 'injected' | 'external' | 'none' | boolean;\n'injected' (formerly true), styles will be included in the JavaScript class and injected at runtime for the components actually rendered.\n'external' (formerly false), the CSS will be returned in the css field of the compilation result. Most Svelte bundler plugins will set this to 'external' and use the CSS that is statically generated for better performance, as it will result in smaller JavaScript bundles and the output can be served as cacheable .css files.\n'none', styles are completely avoided and no CSS output is generated.\n\n\n\nloopGuardTimeout?: number;\n\n\ndefault\n 0\n\n\nA number that tells Svelte to break the loop if it blocks the thread for more than loopGuardTimeout ms.\nThis is useful to prevent infinite loops.\nOnly available when dev: true.\n\n\n\nnamespace?: string;\n\n\ndefault\n 'html'\n\n\nThe namespace of the element; e.g., &quot;mathml&quot;, &quot;svg&quot;, &quot;foreign&quot;.\n\n\n\ncssHash?: CssHashGetter;\n\n\ndefault\n undefined\n\n\nA function that takes a { hash, css, name, filename } argument and returns the string that is used as a classname for scoped CSS.\nIt defaults to returning svelte-${hash(css)}.\n\n\n\npreserveComments?: boolean;\n\n\ndefault\n false\n\n\nIf true, your HTML comments will be preserved during server-side rendering. By default, they are stripped out.\n\n\n\npreserveWhitespace?: boolean;\n\n\ndefault\n false\n\n\nIf true, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.\n\n\n\ndiscloseVersion?: boolean;\n\n\ndefault\n true\n\n\nIf true, exposes the Svelte major version in the browser by adding it to a Set stored in the global window.__svelte.v.","rank":null},{"breadcrumbs":["svelte/compiler","Types","CompileResult"],"href":"/docs/svelte-compiler#types-compileresult","content":"The returned shape of compile from svelte/compiler\n\n\ninterface CompileResult {/*…*/}\njs: {/*…*/}\nThe resulting JavaScript code from compling the component\n\n\ncode: string;\nCode as a string\n\n\nmap: any;\nA source map\n\n\n\ncss: CssResult;\nThe resulting CSS code from compling the component\n\n\n\nast: Ast;\nThe abstract syntax tree representing the structure of the component\n\n\n\nwarnings: Warning[];\nAn array of warning objects that were generated during compilation. Each warning has several properties:\n\ncode is a string identifying the category of warning\nmessage describes the issue in human-readable terms\nstart and end, if the warning relates to a specific location, are objects with line, column and character properties\nframe, if applicable, is a string highlighting the offending code with line numbers\n\n\n\nvars: Var[];\nAn array of the component's declarations used by tooling in the ecosystem (like our ESLint plugin) to infer more information\n\n\n\nstats: {\n    timings: {\n        total: number;\n    };\n};\nAn object used by the Svelte developer team for diagnosing the compiler. Avoid relying on it to stay the same!","rank":null},{"breadcrumbs":["svelte/compiler","Types","CssHashGetter"],"href":"/docs/svelte-compiler#types-csshashgetter","content":"type CssHashGetter = (args: {\n    name: string;\n    filename: string | undefined;\n    css: string;\n    hash: (input: string) => string;\n}) => string;","rank":null},{"breadcrumbs":["svelte/compiler","Types","EnableSourcemap"],"href":"/docs/svelte-compiler#types-enablesourcemap","content":"type EnableSourcemap =\n    | boolean\n    | { js: boolean; css: boolean };","rank":null},{"breadcrumbs":["svelte/compiler","Types","MarkupPreprocessor"],"href":"/docs/svelte-compiler#types-markuppreprocessor","content":"A markup preprocessor that takes a string of code and returns a processed version.\n\n\ntype MarkupPreprocessor = (options: {\n    /**\n     * The whole Svelte file content\n     */\n    content: string;\n    /**\n     * The filename of the Svelte file\n     */\n    filename?: string;\n}) => Processed | void | Promise<Processed | void>;","rank":null},{"breadcrumbs":["svelte/compiler","Types","Preprocessor"],"href":"/docs/svelte-compiler#types-preprocessor","content":"A script/style preprocessor that takes a string of code and returns a processed version.\n\n\ntype Preprocessor = (options: {\n    /**\n     * The script/style tag content\n     */\n    content: string;\n    /**\n     * The attributes on the script/style tag\n     */\n    attributes: Record<string, string | boolean>;\n    /**\n     * The whole Svelte file content\n     */\n    markup: string;\n    /**\n     * The filename of the Svelte file\n     */\n    filename?: string;\n}) => Processed | void | Promise<Processed | void>;","rank":null},{"breadcrumbs":["svelte/compiler","Types","PreprocessorGroup"],"href":"/docs/svelte-compiler#types-preprocessorgroup","content":"A preprocessor group is a set of preprocessors that are applied to a Svelte file.\n\n\ninterface PreprocessorGroup {/*…*/}\nname?: string;\nName of the preprocessor. Will be a required option in the next major version\n\n\n\nmarkup?: MarkupPreprocessor;\n\n\nstyle?: Preprocessor;\n\n\nscript?: Preprocessor;","rank":null},{"breadcrumbs":["svelte/compiler","Types","Processed"],"href":"/docs/svelte-compiler#types-processed","content":"The result of a preprocessor run. If the preprocessor does not return a result, it is assumed that the code is unchanged.\n\n\ninterface Processed {/*…*/}\ncode: string;\nThe new code\n\n\n\nmap?: string | object;\nA source map mapping back to the original code\n\n\n\ndependencies?: string[];\nA list of additional files to watch for changes\n\n\n\nattributes?: Record<string, string | boolean>;\nOnly for script/style preprocessors: The updated attributes to set on the tag. If undefined, attributes stay unchanged.\n\n\n\ntoString?: () => string;","rank":null},{"breadcrumbs":["svelte/compiler","Types","SveltePreprocessor"],"href":"/docs/svelte-compiler#types-sveltepreprocessor","content":"Utility type to extract the type of a preprocessor from a preprocessor group\n\n\ninterface SveltePreprocessor<\n    PreprocessorType extends keyof PreprocessorGroup,\n    Options = any\n> {/*…*/}\n(options?: Options): Required<Pick<PreprocessorGroup, PreprocessorType>>;","rank":null},{"breadcrumbs":["Client-side component API"],"href":"/docs/client-side-component-api","content":"","rank":null},{"breadcrumbs":["Client-side component API","Creating a component"],"href":"/docs/client-side-component-api#creating-a-component","content":"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.\n\nimport App from './App.svelte';\n\nconst app = new App({\n    target: document.body,\n    props: {\n        // assuming App.svelte contains something like\n        // `export let answer`:\n        answer: 42\n    }\n});The following initialisation options can be provided:\n\noption default description \n\nExisting children of target are left where they are.\n\nThe 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. Hydration of <head> 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 <head> so that the component knows which elements it's responsible for removing during hydration.\n\nWhereas 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.\n\nThe existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.\n\nimport App from './App.svelte';\n\nconst app = new App({\n    target: document.querySelector('#server-rendered-html'),\n    hydrate: true\n});","rank":null},{"breadcrumbs":["Client-side component API","$set"],"href":"/docs/client-side-component-api#$set","content":"component.$set(props);Programmatically sets props on an instance. component.$set({ x: 1 }) is equivalent to x = 1 inside the component's <script> block.\n\nCalling this method schedules an update for the next microtask — the DOM is not updated synchronously.\n\ncomponent.$set({ answer: 42 });","rank":null},{"breadcrumbs":["Client-side component API","$on"],"href":"/docs/client-side-component-api#$on","content":"component.$on(ev, callback);Causes the callback function to be called whenever the component dispatches an event.\n\nA function is returned that will remove the event listener when called.\n\nconst off = component.$on('selected', (event) => {\n    console.log(event.detail.selection);\n});\n\noff();","rank":null},{"breadcrumbs":["Client-side component API","$destroy"],"href":"/docs/client-side-component-api#$destroy","content":"component.$destroy();Removes a component from the DOM and triggers any onDestroy handlers.","rank":null},{"breadcrumbs":["Client-side component API","Component props"],"href":"/docs/client-side-component-api#component-props","content":"component.prop;component.prop = value;If a component is compiled with accessors: true, each instance will have getters and setters corresponding to each of the component's props. Setting a value will cause a synchronous update, rather than the default async update caused by component.$set(...).\n\nBy default, accessors is false, unless you're compiling as a custom element.\n\nconsole.log(component.count);\ncomponent.count += 1;","rank":null},{"breadcrumbs":["Server-side component API"],"href":"/docs/server-side-component-api","content":"// @noErrors\nconst result = Component.render(...)Unlike client-side components, server-side components don't have a lifespan after you render them — their whole job is to create some HTML and CSS. For that reason, the API is somewhat different.\n\nA server-side component exposes a render method that can be called with optional props. It returns an object with head, html, and css properties, where head contains the contents of any <svelte:head> elements encountered.\n\nYou can import a Svelte component directly into Node using svelte/register.\n\n// @noErrors\nrequire('svelte/register');\n\nconst App = require('./App.svelte').default;\n\nconst { head, html, css } = App.render({\n    answer: 42\n});The .render() method accepts the following parameters:\n\nparameter default description \n\nThe options object takes in the following options:\n\noption default description \n\n// @noErrors\nconst { head, html, css } = App.render(\n    // props\n    { answer: 42 },\n    // options\n    {\n        context: new Map([['context-key', 'context-value']])\n    }\n);","rank":null},{"breadcrumbs":["Custom elements API"],"href":"/docs/custom-elements-api","content":"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.\n\n<svelte:options customElement=\"my-element\" />\n\n<!-- in Svelte 3, do this instead:\n<svelte:options tag=\"my-element\" />\n-->\n\n<script>\n    export let name = 'world';\n</script>\n\n<h1>Hello {name}!</h1>\n<slot />You can leave out the tag name for any of your inner components which you don't want to expose and use them like regular Svelte components. Consumers of the component can still name it afterwards if needed, using the static element property which contains the custom element constructor and which is available when the customElement compiler option is true.\n\n// @noErrors\nimport MyElement from './MyElement.svelte';\n\ncustomElements.define('my-element', MyElement.element);\n// In Svelte 3, do this instead:\n// customElements.define('my-element', MyElement);Once a custom element has been defined, it can be used as a regular DOM element:\n\ndocument.body.innerHTML = `\n    <my-element>\n        <p>This is some slotted content</p>\n    </my-element>\n`;By default, custom elements are compiled with accessors: true, which means that any props are exposed as properties of the DOM element (as well as being readable/writable as attributes, where possible).\n\nTo prevent this, add accessors={false} to <svelte:options>.\n\n// @noErrors\nconst el = document.querySelector('my-element');\n\n// get the current value of the 'name' prop\nconsole.log(el.name);\n\n// set a new value, updating the shadow DOM\nel.name = 'everybody';","rank":null},{"breadcrumbs":["Custom elements API","Component lifecycle"],"href":"/docs/custom-elements-api#component-lifecycle","content":"Custom elements are created from Svelte components using a wrapper approach. This means the inner Svelte component has no knowledge that it is a custom element. The custom element wrapper takes care of handling its lifecycle appropriately.\n\nWhen a custom element is created, the Svelte component it wraps is not created right away. It is only created in the next tick after the connectedCallback is invoked. Properties assigned to the custom element before it is inserted into the DOM are temporarily saved and then set on component creation, so their values are not lost. The same does not work for invoking exported functions on the custom element though, they are only available after the element has mounted. If you need to invoke functions before component creation, you can work around it by using the extend option.\n\nWhen a custom element written with Svelte is created or updated, the shadow DOM will reflect the value in the next tick, not immediately. This way updates can be batched, and DOM moves which temporarily (but synchronously) detach the element from the DOM don't lead to unmounting the inner component.\n\nThe inner Svelte component is destroyed in the next tick after the disconnectedCallback is invoked.","rank":null},{"breadcrumbs":["Custom elements API","Component options"],"href":"/docs/custom-elements-api#component-options","content":"When constructing a custom element, you can tailor several aspects by defining customElement as an object within <svelte:options> since Svelte 4. This object may contain the following properties:\n\ntag: the mandatory tag property for the custom element's name\nshadow: an optional property that can be set to &quot;none&quot; to forgo shadow root creation. Note that styles are then no longer encapsulated, and you can't use slots\nprops: an optional property to modify certain details and behaviors of your component's properties. It offers the following settings:attribute: string: To update a custom element's prop, you have two alternatives: either set the property on the custom element's reference as illustrated above or use an HTML attribute. For the latter, the default attribute name is the lowercase property name. Modify this by assigning attribute: &quot;<desired name>&quot;.\nreflect: boolean: By default, updated prop values do not reflect back to the DOM. To enable this behavior, set reflect: true.\ntype: 'String' | 'Boolean' | 'Number' | 'Array' | 'Object': While converting an attribute value to a prop value and reflecting it back, the prop value is assumed to be a String by default. This may not always be accurate. For instance, for a number type, define it using type: &quot;Number&quot;\nYou don't need to list all properties, those not listed will use the default settings.\n\n\nextend: an optional property which expects a function as its argument. It is passed the custom element class generated by Svelte and expects you to return a custom element class. This comes in handy if you have very specific requirements to the life cycle of the custom element or want to enhance the class to for example use ElementInternals for better HTML form integration.\n\n<svelte:options\n    customElement={{\n        tag: 'custom-element',\n        shadow: 'none',\n        props: {\n            name: { reflect: true, type: 'Number', attribute: 'element-index' }\n        },\n        extend: (customElementConstructor) => {\n            // Extend the class so we can let it participate in HTML forms\n            return class extends customElementConstructor {\n                static formAssociated = true;\n\n                constructor() {\n                    super();\n                    this.attachedInternals = this.attachInternals();\n                }\n\n                // Add the function here, not below in the component so that\n                // it's always available, not just when the inner Svelte component\n                // is mounted\n                randomIndex() {\n                    this.elementIndex = Math.random();\n                }\n            };\n        }\n    }}\n/>\n\n<script>\n    export let elementIndex;\n    export let attachedInternals;\n    // ...\n    function check() {\n        attachedInternals.checkValidity();\n    }\n</script>\n\n...","rank":null},{"breadcrumbs":["Custom elements API","Caveats and limitations"],"href":"/docs/custom-elements-api#caveats-and-limitations","content":"Custom elements can be a useful way to package components for consumption in a non-Svelte app, as they will work with vanilla HTML and JavaScript as well as most frameworks. There are, however, some important differences to be aware of:\n\nStyles are encapsulated, rather than merely scoped (unless you set shadow: &quot;none&quot;). This means that any non-component styles (such as you might have in a global.css file) will not apply to the custom element, including styles with the :global(...) modifier\nInstead of being extracted out as a separate .css file, styles are inlined into the component as a JavaScript string\nCustom elements are not generally suitable for server-side rendering, as the shadow DOM is invisible until JavaScript loads\nIn Svelte, slotted content renders lazily. In the DOM, it renders eagerly. In other words, it will always be created even if the component's <slot> element is inside an {#if ...} block. Similarly, including a <slot> in an {#each ...} block will not cause the slotted content to be rendered multiple times\nThe let: directive has no effect, because custom elements do not have a way to pass data to the parent component that fills the slot\nPolyfills are required to support older browsers\nYou can use Svelte's context feature between regular Svelte components within a custom element, but you can't use them across custom elements. In other words, you can't use setContext on a parent custom element and read that with getContext in a child custom element.","rank":null},{"breadcrumbs":["Frequently asked questions"],"href":"/docs/faq","content":"","rank":null},{"breadcrumbs":["Frequently asked questions","I'm new to Svelte. Where should I start?"],"href":"/docs/faq#i-m-new-to-svelte-where-should-i-start","content":"We think the best way to get started is playing through the interactive 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.\n\nFive to ten minutes should be enough to get you up and running. An hour and a half should get you through the entire tutorial.","rank":null},{"breadcrumbs":["Frequently asked questions","Where can I get support?"],"href":"/docs/faq#where-can-i-get-support","content":"If your question is about certain syntax, the API page is a good place to start.\n\nStack Overflow is a popular forum to ask code-level questions or if you’re stuck with a specific error. Read through the existing questions tagged with Svelte or ask your own!\n\nThere are online forums and chats which are a great place for discussion about best practices, application architecture or just to get to know fellow Svelte users. Our Discord or the Reddit channel are examples of that. If you have an answerable code-level question, Stack Overflow is usually a better fit.","rank":null},{"breadcrumbs":["Frequently asked questions","Are there any third-party resources?"],"href":"/docs/faq#are-there-any-third-party-resources","content":"Svelte Society maintains a list of books and videos.","rank":null},{"breadcrumbs":["Frequently asked questions","How can I get VS Code to syntax-highlight my .svelte files?"],"href":"/docs/faq#how-can-i-get-vs-code-to-syntax-highlight-my-svelte-files","content":"There is an official VS Code extension for Svelte.","rank":null},{"breadcrumbs":["Frequently asked questions","Is there a tool to automatically format my .svelte files?"],"href":"/docs/faq#is-there-a-tool-to-automatically-format-my-svelte-files","content":"You can use prettier with the prettier-plugin-svelte plugin.","rank":null},{"breadcrumbs":["Frequently asked questions","How do I document my components?"],"href":"/docs/faq#how-do-i-document-my-components","content":"In editors which use the Svelte Language Server you can document Components, functions and exports using specially formatted comments.\n\n<script>\n    /** What should we call the user? */\n    export let name = 'world';\n</script>\n\n<!--\n@component\nHere's some documentation for this component.\nIt will show up on hover.\n\n- You can use markdown here.\n- You can also use code blocks here.\n- Usage:\n  ```tsx\n  <main name=\"Arethra\">\n  ```\n-->\n<main>\n    <h1>\n        Hello, {name}\n    </h1>\n</main>Note: The @component is necessary in the HTML comment which describes your component.","rank":null},{"breadcrumbs":["Frequently asked questions","Does Svelte scale?"],"href":"/docs/faq#does-svelte-scale","content":"There will be a blog post about this eventually, but in the meantime, check out this issue.","rank":null},{"breadcrumbs":["Frequently asked questions","Is there a UI component library?"],"href":"/docs/faq#is-there-a-ui-component-library","content":"There are several UI component libraries as well as standalone components. Find them under the design systems section of the components page on the Svelte Society website.","rank":null},{"breadcrumbs":["Frequently asked questions","How do I test Svelte apps?"],"href":"/docs/faq#how-do-i-test-svelte-apps","content":"How your application is structured and where logic is defined will determine the best way to ensure it is properly tested. It is important to note that not all logic belongs within a component - this includes concerns such as data transformation, cross-component state management, and logging, among others. Remember that the Svelte library has its own test suite, so you do not need to write tests to validate implementation details provided by Svelte.\n\nA Svelte application will typically have three different types of tests: Unit, Component, and End-to-End (E2E).\n\nUnit Tests: Focus on testing business logic in isolation. Often this is validating individual functions and edge cases. By minimizing the surface area of these tests they can be kept lean and fast, and by extracting as much logic as possible from your Svelte components more of your application can be covered using them. When creating a new SvelteKit project, you will be asked whether you would like to setup Vitest for unit testing. There are a number of other test runners that could be used as well.\n\nComponent Tests: Validating that a Svelte component mounts and interacts as expected throughout its lifecycle requires a tool that provides a Document Object Model (DOM). Components can be compiled (since Svelte is a compiler and not a normal library) and mounted to allow asserting against element structure, listeners, state, and all the other capabilities provided by a Svelte component. Tools for component testing range from an in-memory implementation like jsdom paired with a test runner like Vitest to solutions that leverage an actual browser to provide a visual testing capability such as Playwright or Cypress.\n\nEnd-to-End Tests: To ensure your users are able to interact with your application it is necessary to test it as a whole in a manner as close to production as possible. This is done by writing end-to-end (E2E) tests which load and interact with a deployed version of your application in order to simulate how the user will interact with your application. When creating a new SvelteKit project, you will be asked whether you would like to setup Playwright for end-to-end testing. There are many other E2E test libraries available for use as well.\n\nSome resources for getting started with testing:\n\nSvelte Testing Library\nSvelte Component Testing in Cypress\nExample using vitest\nExample using uvu test runner with JSDOM\nTest Svelte components using Vitest &amp; Playwright\nComponent testing with WebdriverIO","rank":null},{"breadcrumbs":["Frequently asked questions","Is there a router?"],"href":"/docs/faq#is-there-a-router","content":"The official routing library is SvelteKit. SvelteKit provides a filesystem router, server-side rendering (SSR), and hot module reloading (HMR) in one easy-to-use package. It shares similarities with Next.js for React.\n\nHowever, you can use any router library. A lot of people use page.js. There's also navaid, which is very similar. And universal-router, which is isomorphic with child routes, but without built-in history support.\n\nIf you prefer a declarative HTML approach, there's the isomorphic svelte-routing library and a fork of it called svelte-navigator containing some additional functionality.\n\nIf you need hash-based routing on the client side, check out svelte-spa-router or abstract-state-router.\n\nRoutify is another filesystem-based router, similar to SvelteKit's router. Version 3 supports Svelte's native SSR.\n\nYou can see a community-maintained list of routers on sveltesociety.dev.","rank":null},{"breadcrumbs":["Frequently asked questions","Can I tell Svelte not to remove my unused styles?"],"href":"/docs/faq#can-i-tell-svelte-not-to-remove-my-unused-styles","content":"No. Svelte removes the styles from the component and warns you about them in order to prevent issues that would otherwise arise.\n\nSvelte's component style scoping works by generating a class unique to the given component, adding it to the relevant elements in the component that are under Svelte's control, and then adding it to each of the selectors in that component's styles. When the compiler can't see what elements a style selector applies to, there would be two bad options for keeping it:\n\nIf it keeps the selector and adds the scoping class to it, the selector will likely not match the expected elements in the component, and they definitely won't if they were created by a child component or {@html ...}.\nIf it keeps the selector without adding the scoping class to it, the given style will become a global style, affecting your entire page.\n\nIf you need to style something that Svelte can't identify at compile time, you will need to explicitly opt into global styles by using :global(...). But also keep in mind that you can wrap :global(...) around only part of a selector. .foo :global(.bar) { ... } will style any .bar elements that appear within the component's .foo elements. As long as there's some parent element in the current component to start from, partially global selectors like this will almost always be able to get you what you want.","rank":null},{"breadcrumbs":["Frequently asked questions","Is Svelte v2 still available?"],"href":"/docs/faq#is-svelte-v2-still-available","content":"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.\n\nThe documentation is still available here.","rank":null},{"breadcrumbs":["Frequently asked questions","How do I do hot module reloading?"],"href":"/docs/faq#how-do-i-do-hot-module-reloading","content":"We recommend using SvelteKit, which supports HMR out of the box and is built on top of Vite and svelte-hmr. There are also community plugins for rollup and webpack.","rank":null},{"breadcrumbs":["Accessibility warnings"],"href":"/docs/accessibility-warnings","content":"Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you at compile time if you write inaccessible markup. However, keep in mind that many accessibility issues can only be identified at runtime using other automated tools and by manually testing your application.\n\nSome warnings may be incorrect in your concrete use case. You can disable such false positives by placing a <!-- svelte-ignore a11y-<code> --> comment above the line that causes the warning. Example:\n\n<!-- svelte-ignore a11y-autofocus -->\n<input autofocus />You can list multiple rules in a single comment, and add an explanatory note alongside them:\n\n<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-static-element-interactions (because of reasons) -->\n<div on:click>...</div>Here is a list of accessibility checks Svelte will do for you.","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-accesskey"],"href":"/docs/accessibility-warnings#a11y-accesskey","content":"Enforce no accesskey on element. Access keys are HTML attributes that allow web developers to assign keyboard shortcuts to elements. Inconsistencies between keyboard shortcuts and keyboard commands used by screen reader and keyboard-only users create accessibility complications. To avoid complications, access keys should not be used.\n\n\n<!-- A11y: Avoid using accesskey -->\n<div accessKey=\"z\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-aria-activedescendant-has-tabindex"],"href":"/docs/accessibility-warnings#a11y-aria-activedescendant-has-tabindex","content":"An element with aria-activedescendant must be tabbable, so it must either have an inherent tabindex or declare tabindex as an attribute.\n\n<!-- A11y: Elements with attribute aria-activedescendant should have tabindex value -->\n<div aria-activedescendant=\"some-id\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-aria-attributes"],"href":"/docs/accessibility-warnings#a11y-aria-attributes","content":"Certain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example meta, html, script, style. This rule enforces that these DOM elements do not contain the aria-* props.\n\n<!-- A11y: <meta> should not have aria-* attributes -->\n<meta aria-hidden=\"false\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-autofocus"],"href":"/docs/accessibility-warnings#a11y-autofocus","content":"Enforce that autofocus is not used on elements. Autofocusing elements can cause usability issues for sighted and non-sighted users alike.\n\n<!-- A11y: Avoid using autofocus -->\n<input autofocus />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-click-events-have-key-events"],"href":"/docs/accessibility-warnings#a11y-click-events-have-key-events","content":"Enforce that visible, non-interactive elements with an on:click event are accompanied by a keyboard event handler.\n\nUsers should first consider whether an interactive element might be more appropriate such as a <button type=&quot;button&quot;> element for actions or <a> element for navigations. These elements are more semantically meaningful and will have built-in key handling. E.g. Space and Enter will trigger a <button> and Enter will trigger an <a> element.\n\nIf a non-interactive element is required then on:click should be accompanied by an on:keyup or on:keydown handler that enables the user to perform equivalent actions via the keyboard. In order for the user to be able to trigger a key press, the element will also need to be focusable by adding a tabindex. While an on:keypress handler will also silence this warning, it should be noted that the keypress event is deprecated.\n\n<!-- A11y: visible, non-interactive elements with an on:click event must be accompanied by a keyboard event handler. -->\n<div on:click={() => {}} />Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users.","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-distracting-elements"],"href":"/docs/accessibility-warnings#a11y-distracting-elements","content":"Enforces that no distracting elements are used. Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided.\n\nThe following elements are visually distracting: <marquee> and <blink>.\n\n<!-- A11y: Avoid <marquee> elements -->\n<marquee />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-hidden"],"href":"/docs/accessibility-warnings#a11y-hidden","content":"Certain DOM elements are useful for screen reader navigation and should not be hidden.\n\n\n<!-- A11y: <h2> element should not be hidden -->\n<h2 aria-hidden=\"true\">invisible header</h2>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-img-redundant-alt"],"href":"/docs/accessibility-warnings#a11y-img-redundant-alt","content":"Enforce img alt attribute does not contain the word image, picture, or photo. Screen readers already announce img elements as an image. There is no need to use words such as image, photo, and/or picture.\n\n<img src=\"foo\" alt=\"Foo eating a sandwich.\" />\n\n<!-- aria-hidden, won't be announced by screen reader -->\n<img src=\"bar\" aria-hidden=\"true\" alt=\"Picture of me taking a photo of an image\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"foo\" alt=\"Photo of foo being weird.\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"bar\" alt=\"Image of me at a bar!\" />\n\n<!-- A11y: Screen readers already announce <img> elements as an image. -->\n<img src=\"foo\" alt=\"Picture of baz fixing a bug.\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-incorrect-aria-attribute-type"],"href":"/docs/accessibility-warnings#a11y-incorrect-aria-attribute-type","content":"Enforce that only the correct type of value is used for aria attributes. For example, aria-hidden\nshould only receive a boolean.\n\n<!-- A11y: The value of 'aria-hidden' must be exactly one of true or false -->\n<div aria-hidden=\"yes\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-invalid-attribute"],"href":"/docs/accessibility-warnings#a11y-invalid-attribute","content":"Enforce that attributes important for accessibility have a valid value. For example, href should not be empty, '#', or javascript:.\n\n<!-- A11y: '' is not a valid href attribute -->\n<a href=\"\">invalid</a>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-interactive-supports-focus"],"href":"/docs/accessibility-warnings#a11y-interactive-supports-focus","content":"Enforce that elements with an interactive role and interactive handlers (mouse or key press) must be focusable or tabbable.\n\n<!-- A11y: Elements with the 'button' interactive role must have a tabindex value. -->\n<div role=\"button\" on:keypress={() => {}} />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-label-has-associated-control"],"href":"/docs/accessibility-warnings#a11y-label-has-associated-control","content":"Enforce that a label tag has a text label and an associated control.\n\nThere are two supported ways to associate a label with a control:\n\nWrapping a control in a label tag.\nAdding for to a label and assigning it the ID of an input on the page.\n\n<label for=\"id\">B</label>\n\n<label>C <input type=\"text\" /></label>\n\n<!-- A11y: A form label must be associated with a control. -->\n<label>A</label>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-media-has-caption"],"href":"/docs/accessibility-warnings#a11y-media-has-caption","content":"Providing captions for media is essential for deaf users to follow along. Captions should be a transcription or translation of the dialogue, sound effects, relevant musical cues, and other relevant audio information. Not only is this important for accessibility, but can also be useful for all users in the case that the media is unavailable (similar to alt text on an image when an image is unable to load).\n\nThe captions should contain all important and relevant information to understand the corresponding media. This may mean that the captions are not a 1:1 mapping of the dialogue in the media content. However, captions are not necessary for video components with the muted attribute.\n\n<video><track kind=\"captions\" /></video>\n\n<audio muted />\n\n<!-- A11y: Media elements must have a <track kind=\\\"captions\\\"> -->\n<video />\n\n<!-- A11y: Media elements must have a <track kind=\\\"captions\\\"> -->\n<video><track /></video>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-misplaced-role"],"href":"/docs/accessibility-warnings#a11y-misplaced-role","content":"Certain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example meta, html, script, style. This rule enforces that these DOM elements do not contain the role props.\n\n<!-- A11y: <meta> should not have role attribute -->\n<meta role=\"tooltip\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-misplaced-scope"],"href":"/docs/accessibility-warnings#a11y-misplaced-scope","content":"The scope attribute should only be used on <th> elements.\n\n\n<!-- A11y: The scope attribute should only be used with <th> elements -->\n<div scope=\"row\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-missing-attribute"],"href":"/docs/accessibility-warnings#a11y-missing-attribute","content":"Enforce that attributes required for accessibility are present on an element. This includes the following checks:\n\n<a> should have an href (unless it's a fragment-defining tag)\n<area> should have alt, aria-label, or aria-labelledby\n<html> should have lang\n<iframe> should have title\n<img> should have alt\n<object> should have title, aria-label, or aria-labelledby\n<input type=&quot;image&quot;> should have alt, aria-label, or aria-labelledby\n\n<!-- A11y: <input type=\\\"image\\\"> element should have an alt, aria-label or aria-labelledby attribute -->\n<input type=\"image\" />\n\n<!-- A11y: <html> element should have a lang attribute -->\n<html />\n\n<!-- A11y: <a> element should have an href attribute -->\n<a>text</a>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-missing-content"],"href":"/docs/accessibility-warnings#a11y-missing-content","content":"Enforce that heading elements (h1, h2, etc.) and anchors have content and that the content is accessible to screen readers\n\n<!-- A11y: <a> element should have child content -->\n<a href=\"/foo\" />\n\n<!-- A11y: <h1> element should have child content -->\n<h1 />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-mouse-events-have-key-events"],"href":"/docs/accessibility-warnings#a11y-mouse-events-have-key-events","content":"Enforce that on:mouseover and on:mouseout are accompanied by on:focus and on:blur, respectively. This helps to ensure that any functionality triggered by these mouse events is also accessible to keyboard users.\n\n<!-- A11y: on:mouseover must be accompanied by on:focus -->\n<div on:mouseover={handleMouseover} />\n\n<!-- A11y: on:mouseout must be accompanied by on:blur -->\n<div on:mouseout={handleMouseout} />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-redundant-roles"],"href":"/docs/accessibility-warnings#a11y-no-redundant-roles","content":"Some HTML elements have default ARIA roles. Giving these elements an ARIA role that is already set by the browser has no effect and is redundant.\n\n<!-- A11y: Redundant role 'button' -->\n<button role=\"button\" />\n\n<!-- A11y: Redundant role 'img' -->\n<img role=\"img\" src=\"foo.jpg\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-interactive-element-to-noninteractive-role"],"href":"/docs/accessibility-warnings#a11y-no-interactive-element-to-noninteractive-role","content":"WAI-ARIA roles should not be used to convert an interactive element to a non-interactive element. Non-interactive ARIA roles include article, banner, complementary, img, listitem, main, region and tooltip.\n\n<!-- A11y: <textarea> cannot have role 'listitem' -->\n<textarea role=\"listitem\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-interactive-element-to-noninteractive-role","a11y-no-noninteractive-element-interactions"],"href":"/docs/accessibility-warnings#a11y-no-interactive-element-to-noninteractive-role-a11y-no-noninteractive-element-interactions","content":"A non-interactive element does not support event handlers (mouse and key handlers). Non-interactive elements include <main>, <area>, <h1> (,<h2>, etc), <p>, <img>, <li>, <ul> and <ol>. Non-interactive WAI-ARIA roles include article, banner, complementary, img, listitem, main, region and tooltip.\n\n<!-- `A11y: Non-interactive element <li> should not be assigned mouse or keyboard event listeners.` -->\n<li on:click={() => {}} />\n\n<!-- `A11y: Non-interactive element <div> should not be assigned mouse or keyboard event listeners.` -->\n<div role=\"listitem\" on:click={() => {}} />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-interactive-element-to-noninteractive-role","a11y-no-noninteractive-element-to-interactive-role"],"href":"/docs/accessibility-warnings#a11y-no-interactive-element-to-noninteractive-role-a11y-no-noninteractive-element-to-interactive-role","content":"WAI-ARIA roles should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include button, link, checkbox, menuitem, menuitemcheckbox, menuitemradio, option, radio, searchbox, switch and textbox.\n\n<!-- A11y: Non-interactive element <h3> cannot have interactive role 'searchbox' -->\n<h3 role=\"searchbox\">Button</h3>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-noninteractive-tabindex"],"href":"/docs/accessibility-warnings#a11y-no-noninteractive-tabindex","content":"Tab key navigation should be limited to elements on the page that can be interacted with.\n\n\n<!-- A11y: noninteractive element cannot have nonnegative tabIndex value -->\n<div tabindex=\"0\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-no-static-element-interactions"],"href":"/docs/accessibility-warnings#a11y-no-static-element-interactions","content":"Elements like <div> with interactive handlers like click must have an ARIA role.\n\n\n<!-- A11y: <div> with click handler must have an ARIA role -->\n<div on:click={() => ''} />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-positive-tabindex"],"href":"/docs/accessibility-warnings#a11y-positive-tabindex","content":"Avoid positive tabindex property values. This will move elements out of the expected tab order, creating a confusing experience for keyboard users.\n\n\n<!-- A11y: avoid tabindex values above zero -->\n<div tabindex=\"1\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-role-has-required-aria-props"],"href":"/docs/accessibility-warnings#a11y-role-has-required-aria-props","content":"Elements with ARIA roles must have all required attributes for that role.\n\n<!-- A11y: A11y: Elements with the ARIA role \"checkbox\" must have the following attributes defined: \"aria-checked\" -->\n<span role=\"checkbox\" aria-labelledby=\"foo\" tabindex=\"0\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-role-supports-aria-props"],"href":"/docs/accessibility-warnings#a11y-role-supports-aria-props","content":"Elements with explicit or implicit roles defined contain only aria-* properties supported by that role.\n\n<!-- A11y: The attribute 'aria-multiline' is not supported by the role 'link'. -->\n<div role=\"link\" aria-multiline />\n\n<!-- A11y: The attribute 'aria-required' is not supported by the role 'listitem'. This role is implicit on the element <li>. -->\n<li aria-required />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-structure"],"href":"/docs/accessibility-warnings#a11y-structure","content":"Enforce that certain DOM elements have the correct structure.\n\n<!-- A11y: <figcaption> must be an immediate child of <figure> -->\n<div>\n    <figcaption>Image caption</figcaption>\n</div>","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-unknown-aria-attribute"],"href":"/docs/accessibility-warnings#a11y-unknown-aria-attribute","content":"Enforce that only known ARIA attributes are used. This is based on the WAI-ARIA States and Properties spec.\n\n<!-- A11y: Unknown aria attribute 'aria-labeledby' (did you mean 'labelledby'?) -->\n<input type=\"image\" aria-labeledby=\"foo\" />","rank":null},{"breadcrumbs":["Accessibility warnings","a11y-unknown-role"],"href":"/docs/accessibility-warnings#a11y-unknown-role","content":"Elements with ARIA roles must use a valid, non-abstract ARIA role. A reference to role definitions can be found at WAI-ARIA site.\n\n\n<!-- A11y: Unknown role 'toooltip' (did you mean 'tooltip'?) -->\n<div role=\"toooltip\" />","rank":null},{"breadcrumbs":["TypeScript"],"href":"/docs/typescript","content":"You can use TypeScript within Svelte components. IDE extensions like the Svelte VSCode extension will help you catch errors right in your editor, and svelte-check does the same on the command line, which you can integrate into your CI.","rank":null},{"breadcrumbs":["TypeScript","Setup"],"href":"/docs/typescript#setup","content":"To use TypeScript within Svelte components, you need to add a preprocessor that will turn TypeScript into JavaScript.","rank":null},{"breadcrumbs":["TypeScript","Setup","Using SvelteKit or Vite"],"href":"/docs/typescript#setup-using-sveltekit-or-vite","content":"The easiest way to get started is scaffolding a new SvelteKit project by typing npm create svelte@latest, following the prompts and choosing the TypeScript option.\n\nIf you don't need or want all the features SvelteKit has to offer, you can scaffold a Svelte-flavoured Vite project instead by typing npm create vite@latest and selecting the svelte-ts option.\n\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\n\nconst config = {\n    preprocess: vitePreprocess()\n};\n\nexport default config;In both cases, a svelte.config.js with vitePreprocess will be added. Vite/SvelteKit will read from this config file.","rank":null},{"breadcrumbs":["TypeScript","Setup","Other build tools"],"href":"/docs/typescript#setup-other-build-tools","content":"If you're using tools like Rollup or Webpack instead, install their respective Svelte plugins. For Rollup that's rollup-plugin-svelte and for Webpack that's svelte-loader. For both, you need to install typescript and svelte-preprocess and add the preprocessor to the plugin config (see the respective READMEs for more info). If you're starting a new project, you can also use the rollup or webpack template to scaffold the setup from a script.\n\nIf you're starting a new project, we recommend using SvelteKit or Vite instead","rank":null},{"breadcrumbs":["TypeScript","<script lang=\"ts\">"],"href":"/docs/typescript#script-lang-ts","content":"To use TypeScript inside your Svelte components, add lang=&quot;ts&quot; to your script tags:\n\n<script lang=\"ts\">\n    let name: string = 'world';\n\n    function greet(name: string) {\n        alert(`Hello, ${name}!`);\n    }\n</script>","rank":null},{"breadcrumbs":["TypeScript","<script lang=\"ts\">","Props"],"href":"/docs/typescript#script-lang-ts-props","content":"Props can be typed directly on the export let statement:\n\n<script lang=\"ts\">\n    export let name: string;\n</script>","rank":null},{"breadcrumbs":["TypeScript","<script lang=\"ts\">","Slots"],"href":"/docs/typescript#script-lang-ts-slots","content":"Slot and slot prop types are inferred from the types of the slot props passed to them:\n\n<script lang=\"ts\">\n    export let name: string;\n</script>\n\n<slot {name} />\n\n<!-- Later -->\n<Comp let:name>\n    <!--    ^ Inferred as string -->\n    {name}\n</Comp>","rank":null},{"breadcrumbs":["TypeScript","<script lang=\"ts\">","Events"],"href":"/docs/typescript#script-lang-ts-events","content":"Events can be typed with createEventDispatcher:\n\n<script lang=\"ts\">\n    import { createEventDispatcher } from 'svelte';\n\n    const dispatch = createEventDispatcher<{\n        event: null; // does not accept a payload\n        click: string; // has a required string payload\n        type: string | null; // has an optional string payload\n    }>();\n\n    function handleClick() {\n        dispatch('event');\n        dispatch('click', 'hello');\n    }\n\n    function handleType() {\n        dispatch('event');\n        dispatch('type', Math.random() > 0.5 ? 'world' : null);\n    }\n</script>\n\n<button on:click={handleClick} on:keydown={handleType}>Click</button>","rank":null},{"breadcrumbs":["TypeScript","Enhancing built-in DOM types"],"href":"/docs/typescript#enhancing-built-in-dom-types","content":"Svelte provides a best effort of all the HTML DOM types that exist. Sometimes you may want to use experimental attributes or custom events coming from an action. In these cases, TypeScript will throw a type error, saying that it does not know these types. If it's a non-experimental standard attribute/event, this may very well be a missing typing from our HTML typings. In that case, you are welcome to open an issue and/or a PR fixing it.\n\nIn case this is a custom or experimental attribute/event, you can enhance the typings like this:\n\n/// file: additional-svelte-typings.d.ts\ndeclare namespace svelteHTML {\n    // enhance elements\n    interface IntrinsicElements {\n        'my-custom-element': { someattribute: string; 'on:event': (e: CustomEvent<any>) => void };\n    }\n    // enhance attributes\n    interface HTMLAttributes<T> {\n        // If you want to use on:beforeinstallprompt\n        'on:beforeinstallprompt'?: (event: any) => any;\n        // If you want to use myCustomAttribute={..} (note: all lowercase)\n        mycustomattribute?: any; // You can replace any with something more specific if you like\n    }\n}Then make sure that d.ts file is referenced in your tsconfig.json. If it reads something like &quot;include&quot;: [&quot;src/**/*&quot;] and your d.ts file is inside src, it should work. You may need to reload for the changes to take effect.\n\nSince Svelte version 4.2 / svelte-check version 3.5 / VS Code extension version 107.10.0 you can also declare the typings by augmenting the svelte/elements module like this:\n\n/// file: additional-svelte-typings.d.ts\nimport { HTMLButtonAttributes } from 'svelte/elements';\n\ndeclare module 'svelte/elements' {\n    export interface SvelteHTMLElements {\n        'custom-button': HTMLButtonAttributes;\n    }\n\n    // allows for more granular control over what element to add the typings to\n    export interface HTMLButtonAttributes {\n        veryexperimentalattribute?: string;\n    }\n}\n\nexport {}; // ensure this is not an ambient module, else types will be overridden instead of augmented","rank":null},{"breadcrumbs":["TypeScript","Experimental advanced typings"],"href":"/docs/typescript#experimental-advanced-typings","content":"A few features are missing from taking full advantage of TypeScript in more advanced use cases like typing that a component implements a certain interface, explicitly typing slots, or using generics. These things are possible using experimental advanced type capabilities. See this RFC for more information on how to make use of them.\n\nThe API is experimental and may change at any point","rank":null},{"breadcrumbs":["TypeScript","Limitations"],"href":"/docs/typescript#limitations","content":"","rank":null},{"breadcrumbs":["TypeScript","Limitations","No TS in markup"],"href":"/docs/typescript#limitations-no-ts-in-markup","content":"You cannot use TypeScript in your template's markup. For example, the following does not work:\n\n<script lang=\"ts\">\n    let count = 10;\n</script>\n\n<h1>Count as string: {count as string}!</h1> <!-- ❌ Does not work -->\n{#if count > 4}\n    {@const countString: string = count} <!-- ❌ Does not work -->\n    {countString}\n{/if}","rank":null},{"breadcrumbs":["TypeScript","Limitations","Reactive Declarations"],"href":"/docs/typescript#limitations-reactive-declarations","content":"You cannot type your reactive declarations with TypeScript in the way you type a variable. For example, the following does not work:\n\n<script lang=\"ts\">\n    let count = 0;\n\n    $: doubled: number = count * 2; // ❌ Does not work\n</script>You cannot add a : TYPE because it's invalid syntax in this position. Instead, you can move the definition to a let statement just above:\n\n<script lang=\"ts\">\n    let count = 0;\n\n    let doubled: number;\n    $: doubled = count * 2;\n</script>","rank":null},{"breadcrumbs":["TypeScript","Types"],"href":"/docs/typescript#types","content":"","rank":null},{"breadcrumbs":["TypeScript","Types","ComponentConstructorOptions"],"href":"/docs/typescript#types-componentconstructoroptions","content":"interface ComponentConstructorOptions<\n    Props extends Record<string, any> = Record<string, any>\n> {/*…*/}\ntarget: Element | Document | ShadowRoot;\n\n\nanchor?: Element;\n\n\nprops?: Props;\n\n\ncontext?: Map<any, any>;\n\n\nhydrate?: boolean;\n\n\nintro?: boolean;\n\n\n$$inline?: boolean;","rank":null},{"breadcrumbs":["TypeScript","Types","ComponentEvents"],"href":"/docs/typescript#types-componentevents","content":"Convenience type to get the events the given component expects. Example:\n\n<script lang=\"ts\">\n   import type { ComponentEvents } from 'svelte';\n   import Component from './Component.svelte';\n\n   function handleCloseEvent(event: ComponentEvents<Component>['close']) {\n      console.log(event.detail);\n   }\n</script>\n\n<Component on:close={handleCloseEvent} />\ntype ComponentEvents<Component extends SvelteComponent_1> =\n    Component extends SvelteComponent<any, infer Events>\n        ? Events\n        : never;","rank":null},{"breadcrumbs":["TypeScript","Types","ComponentProps"],"href":"/docs/typescript#types-componentprops","content":"Convenience type to get the props the given component expects. Example:\n\n<script lang=\"ts\">\n    import type { ComponentProps } from 'svelte';\n    import Component from './Component.svelte';\n\n    const props: ComponentProps<Component> = { foo: 'bar' }; // Errors if these aren't the correct props\n</script>\ntype ComponentProps<Component extends SvelteComponent_1> =\n    Component extends SvelteComponent<infer Props>\n        ? Props\n        : never;","rank":null},{"breadcrumbs":["TypeScript","Types","ComponentType"],"href":"/docs/typescript#types-componenttype","content":"Convenience type to get the type of a Svelte component. Useful for example in combination with\ndynamic components using <svelte:component>.\n\nExample:\n\n<script lang=\"ts\">\n    import type { ComponentType, SvelteComponent } from 'svelte';\n    import Component1 from './Component1.svelte';\n    import Component2 from './Component2.svelte';\n\n    const component: ComponentType = someLogic() ? Component1 : Component2;\n    const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;\n</script>\n\n<svelte:component this={component} />\n<svelte:component this={componentOfCertainSubType} needsThisProp=\"hello\" />\ntype ComponentType<\n    Component extends SvelteComponent = SvelteComponent\n> = (new (\n    options: ComponentConstructorOptions<\n        Component extends SvelteComponent<infer Props>\n            ? Props\n            : Record<string, any>\n    >\n) => Component) & {\n    /** The custom element version of the component. Only present if compiled with the `customElement` compiler option */\n    element?: typeof HTMLElement;\n};","rank":null},{"breadcrumbs":["TypeScript","Types","SvelteComponent"],"href":"/docs/typescript#types-sveltecomponent","content":"Base class for Svelte components with some minor dev-enhancements. Used when dev=true.\n\nCan be used to create strongly typed Svelte components.","rank":null},{"breadcrumbs":["TypeScript","Types","Example:"],"href":"/docs/typescript#types-example","content":"You have component library on npm called component-library, from which\nyou export a component called MyComponent. For Svelte+TypeScript users,\nyou want to provide typings. Therefore you create a index.d.ts:\n\nimport { SvelteComponent } from \"svelte\";\nexport class MyComponent extends SvelteComponent<{foo: string}> {}Typing this makes it possible for IDEs like VS Code with the Svelte extension\nto provide intellisense and to use the component like this in a Svelte file\nwith TypeScript:\n\n<script lang=\"ts\">\n    import { MyComponent } from \"component-library\";\n</script>\n<MyComponent foo={'bar'} />\nclass SvelteComponent<\n    Props extends Record<string, any> = any,\n    Events extends Record<string, any> = any,\n    Slots extends Record<string, any> = any\n> extends SvelteComponent_1<Props, Events> {/*…*/}\n[prop: string]: any;\n\n\nconstructor(options: ComponentConstructorOptions<Props>);\n\n\n$capture_state(): void;\n\n\n$inject_state(): void;","rank":null},{"breadcrumbs":["TypeScript","Types","SvelteComponentTyped"],"href":"/docs/typescript#types-sveltecomponenttyped","content":"class SvelteComponentTyped<\n    Props extends Record<string, any> = any,\n    Events extends Record<string, any> = any,\n    Slots extends Record<string, any> = any\n> extends SvelteComponent<Props, Events, Slots> {}","rank":null},{"breadcrumbs":["Svelte 4 migration guide"],"href":"/docs/v4-migration-guide","content":"This migration guide provides an overview of how to migrate from Svelte version 3 to 4. See the linked PRs for more details about each change. Use the migration script to migrate some of these automatically: npx svelte-migrate@latest svelte-4\n\nIf you're a library author, consider whether to only support Svelte 4 or if it's possible to support Svelte 3 too. Since most of the breaking changes don't affect many people, this may be easily possible. Also remember to update the version range in your peerDependencies.","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Minimum version requirements"],"href":"/docs/v4-migration-guide#minimum-version-requirements","content":"Upgrade to Node 16 or higher. Earlier versions are no longer supported. (#8566)\nIf you are using SvelteKit, upgrade to 1.20.4 or newer (sveltejs/kit#10172)\nIf you are using Vite without SvelteKit, upgrade to vite-plugin-svelte 2.4.1 or newer (#8516)\nIf you are using webpack, upgrade to webpack 5 or higher and svelte-loader 3.1.8 or higher. Earlier versions are no longer supported. (#8515, 198dbcf)\nIf you are using Rollup, upgrade to rollup-plugin-svelte 7.1.5 or higher (198dbcf)\nIf you are using TypeScript, upgrade to TypeScript 5 or higher. Lower versions might still work, but no guarantees are made about that. (#8488)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Browser conditions for bundlers"],"href":"/docs/v4-migration-guide#browser-conditions-for-bundlers","content":"Bundlers must now specify the browser condition when building a frontend bundle for the browser. SvelteKit and Vite will handle this automatically for you. If you're using any others, you may observe lifecycle callbacks such as onMount not get called and you'll need to update the module resolution configuration.\n\nFor Rollup this is done within the @rollup/plugin-node-resolve plugin by setting browser: true in its options. See the rollup-plugin-svelte documentation for more details\nFor webpack this is done by adding &quot;browser&quot; to the conditionNames array. You may also have to update your alias config, if you have set it. See the svelte-loader documentation for more details\n\n(#8516)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Removal of CJS related output"],"href":"/docs/v4-migration-guide#removal-of-cjs-related-output","content":"Svelte no longer supports the CommonJS (CJS) format for compiler output and has also removed the svelte/register hook and the CJS runtime version. If you need to stay on the CJS output format, consider using a bundler to convert Svelte's ESM output to CJS in a post-build step. (#8613)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Stricter types for Svelte functions"],"href":"/docs/v4-migration-guide#stricter-types-for-svelte-functions","content":"There are now stricter types for createEventDispatcher, Action, ActionReturn, and onMount:\n\ncreateEventDispatcher now supports specifying that a payload is optional, required, or non-existent, and the call sites are checked accordingly (#7224)\n\n// @errors: 2554 2345\nimport { createEventDispatcher } from 'svelte';\n\nconst dispatch = createEventDispatcher<{\n    optional: number | null;\n    required: string;\n    noArgument: null;\n}>();\n\n// Svelte version 3:\ndispatch('optional');\ndispatch('required'); // I can still omit the detail argument\ndispatch('noArgument', 'surprise'); // I can still add a detail argument\n\n// Svelte version 4 using TypeScript strict mode:\ndispatch('optional');\ndispatch('required'); // error, missing argument\ndispatch('noArgument', 'surprise'); // error, cannot pass an argumentAction and ActionReturn have a default parameter type of undefined now, which means you need to type the generic if you want to specify that this action receives a parameter. The migration script will migrate this automatically (#7442)\n\n-const action: Action = (node, params) => { .. } // this is now an error if you use params in any way\n+const action: Action<HTMLElement, string> = (node, params) => { .. } // params is of type stringonMount now shows a type error if you return a function asynchronously from it, because this is likely a bug in your code where you expect the callback to be called on destroy, which it will only do for synchronously returned functions (#8136)\n\n// Example where this change reveals an actual bug\nonMount(\n- // someCleanup() not called because function handed to onMount is async\n- async () => {\n-   const something = await foo();\n+ // someCleanup() is called because function handed to onMount is sync\n+ () => {\n+  foo().then(something =>  ..\n   // ..\n   return () => someCleanup();\n}\n);","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Custom Elements with Svelte"],"href":"/docs/v4-migration-guide#custom-elements-with-svelte","content":"The creation of custom elements with Svelte has been overhauled and significantly improved. The tag option is deprecated in favor of the new customElement option:\n\n-<svelte:options tag=\"my-component\" />\n+<svelte:options customElement=\"my-component\" />This change was made to allow more configurability for advanced use cases. The migration script will adjust your code automatically. The update timing of properties has changed slightly as well. (#8457)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","SvelteComponentTyped is deprecated"],"href":"/docs/v4-migration-guide#sveltecomponenttyped-is-deprecated","content":"SvelteComponentTyped is deprecated, as SvelteComponent now has all its typing capabilities. Replace all instances of SvelteComponentTyped with SvelteComponent.\n\n- import { SvelteComponentTyped } from 'svelte';\n+ import { SvelteComponent } from 'svelte';\n\n- export class Foo extends SvelteComponentTyped<{ aProp: string }> {}\n+ export class Foo extends SvelteComponent<{ aProp: string }> {}If you have used SvelteComponent as the component instance type previously, you may see a somewhat opaque type error now, which is solved by changing : typeof SvelteComponent to : typeof SvelteComponent<any>.\n\n<script>\n  import ComponentA from './ComponentA.svelte';\n  import ComponentB from './ComponentB.svelte';\n  import { SvelteComponent } from 'svelte';\n\n-  let component: typeof SvelteComponent;\n+  let component: typeof SvelteComponent<any>;\n\n  function choseRandomly() {\n    component = Math.random() > 0.5 ? ComponentA : ComponentB;\n  }\n</script>\n\n<button on:click={choseRandomly}>random</button>\n<svelte:element this={component} />The migration script will do both automatically for you. (#8512)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Transitions are local by default"],"href":"/docs/v4-migration-guide#transitions-are-local-by-default","content":"Transitions are now local by default to prevent confusion around page navigations. &quot;local&quot; means that a transition will not play if it's within a nested control flow block (each/if/await/key) and not the direct parent block but a block above it is created/destroyed. In the following example, the slide intro animation will only play when success goes from false to true, but it will not play when show goes from false to true:\n\n{#if show}\n    ...\n    {#if success}\n        <p in:slide>Success</p>\n    {/each}\n{/if}To make transitions global, add the |global modifier - then they will play when any control flow block above is created/destroyed. The migration script will do this automatically for you. (#6686)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Default slot bindings"],"href":"/docs/v4-migration-guide#default-slot-bindings","content":"Default slot bindings are no longer exposed to named slots and vice versa:\n\n<script>\n    import Nested from './Nested.svelte';\n</script>\n\n<Nested let:count>\n    <p>\n        count in default slot - is available: {count}\n    </p>\n    <p slot=\"bar\">\n        count in bar slot - is not available: {count}\n    </p>\n</Nested>This makes slot bindings more consistent as the behavior is undefined when for example the default slot is from a list and the named slot is not. (#6049)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Preprocessors"],"href":"/docs/v4-migration-guide#preprocessors","content":"The order in which preprocessors are applied has changed. Now, preprocessors are executed in order, and within one group, the order is markup, script, style.\n\n// @errors: 2304\nimport { preprocess } from 'svelte/compiler';\n\nconst { code } = await preprocess(\n    source,\n    [\n        {\n            markup: () => {\n                console.log('markup-1');\n            },\n            script: () => {\n                console.log('script-1');\n            },\n            style: () => {\n                console.log('style-1');\n            }\n        },\n        {\n            markup: () => {\n                console.log('markup-2');\n            },\n            script: () => {\n                console.log('script-2');\n            },\n            style: () => {\n                console.log('style-2');\n            }\n        }\n    ],\n    {\n        filename: 'App.svelte'\n    }\n);\n\n// Svelte 3 logs:\n// markup-1\n// markup-2\n// script-1\n// script-2\n// style-1\n// style-2\n\n// Svelte 4 logs:\n// markup-1\n// script-1\n// style-1\n// markup-2\n// script-2\n// style-2This could affect you for example if you are using MDsveX - in which case you should make sure it comes before any script or style preprocessor.\n\npreprocess: [\n-\tvitePreprocess(),\n-\tmdsvex(mdsvexConfig)\n+\tmdsvex(mdsvexConfig),\n+\tvitePreprocess()\n]Each preprocessor must also have a name. (#8618)","rank":null},{"breadcrumbs":["Svelte 4 migration guide","New eslint package"],"href":"/docs/v4-migration-guide#new-eslint-package","content":"eslint-plugin-svelte3 is deprecated. It may still work with Svelte 4 but we make no guarantees about that. We recommend switching to our new package eslint-plugin-svelte. See this Github post for an instruction how to migrate. Alternatively, you can create a new project using npm create svelte@latest, select the eslint (and possibly TypeScript) option and then copy over the related files into your existing project.","rank":null},{"breadcrumbs":["Svelte 4 migration guide","Other breaking changes"],"href":"/docs/v4-migration-guide#other-breaking-changes","content":"the inert attribute is now applied to outroing elements to make them invisible to assistive technology and prevent interaction. (#8628)\nthe runtime now uses classList.toggle(name, boolean) which may not work in very old browsers. Consider using a polyfill if you need to support these browsers. (#8629)\nthe runtime now uses the CustomEvent constructor which may not work in very old browsers. Consider using a polyfill if you need to support these browsers. (#8775)\npeople implementing their own stores from scratch using the StartStopNotifier interface (which is passed to the create function of writable etc) from svelte/store now need to pass an update function in addition to the set function. This has no effect on people using stores or creating stores using the existing Svelte stores. (#6750)\nderived will now throw an error on falsy values instead of stores passed to it. (#7947)\ntype definitions for svelte/internal were removed to further discourage usage of those internal methods which are not public API. Most of these will likely change for Svelte 5\nRemoval of DOM nodes is now batched which slightly changes its order, which might affect the order of events fired if you're using a MutationObserver on these elements (#8763)\nif you enhanced the global typings through the svelte.JSX namespace before, you need to migrate this to use the svelteHTML namespace. Similarly if you used the svelte.JSX namespace to use type definitions from it, you need to migrate those to use the types from svelte/elements instead. You can find more information about what to do here","rank":null},{"breadcrumbs":["svelte/register"],"href":"/docs/svelte-register","content":"This API is removed in Svelte 4. require hooks are deprecated and current Node versions understand ESM. Use a bundler like Vite or our full-stack framework SvelteKit instead to create JavaScript modules from Svelte components.\n\n\nTo render Svelte components in Node.js without bundling, use require('svelte/register'). After that, you can use require to include any .svelte file.\n\n// @noErrors\nrequire('svelte/register');\n\nconst App = require('./App.svelte').default;\n\n// ...\n\nconst { html, css, head } = App.render({ answer: 42 });The .default is necessary because we're converting from native JavaScript modules to the CommonJS modules recognised by Node. Note that if your component imports JavaScript modules, they will fail to load in Node and you will need to use a bundler instead.\n\n\nTo set compile options, or to use a custom file extension, call the register hook as a function:\n\n// @noErrors\nrequire('svelte/register')({\n    extensions: ['.customextension'], // defaults to ['.html', '.svelte']\n    preserveComments: true\n});","rank":null}]}