svelte
- Version 5.16.0
- Published
- 2.48 MB
- 14 dependencies
- MIT license
Install
npm i svelte
yarn add svelte
pnpm add svelte
Overview
Cybernetically enhanced web apps
Index
Functions
Namespaces
svelte
- afterUpdate()
- beforeUpdate()
- Component
- ComponentConstructorOptions
- ComponentEvents
- ComponentInternals
- ComponentProps
- ComponentType
- createEventDispatcher()
- createRawSnippet()
- EventDispatcher
- flushSync()
- getAllContexts()
- getContext()
- hasContext()
- hydrate()
- mount()
- MountOptions
- onDestroy()
- onMount()
- setContext()
- Snippet
- SvelteComponent
- SvelteComponentTyped
- tick()
- unmount()
- untrack()
svelte/compiler.AST
- AnimateDirective
- Attribute
- AttributeLike
- AwaitBlock
- BaseNode
- BindDirective
- Block
- ClassDirective
- Comment
- Component
- ConstTag
- DebugTag
- Directive
- EachBlock
- ElementLike
- ExpressionTag
- Fragment
- HtmlTag
- IfBlock
- KeyBlock
- LetDirective
- OnDirective
- RegularElement
- RenderTag
- Root
- Script
- SlotElement
- SnippetBlock
- SpreadAttribute
- StyleDirective
- SvelteBody
- SvelteBoundary
- SvelteComponent
- SvelteDocument
- SvelteElement
- SvelteFragment
- SvelteHead
- SvelteNode
- SvelteOptions
- SvelteOptionsRaw
- SvelteSelf
- SvelteWindow
- Tag
- TemplateNode
- Text
- TitleElement
- TransitionDirective
- UseDirective
svelte/easing
- backIn()
- backInOut()
- backOut()
- bounceIn()
- bounceInOut()
- bounceOut()
- circIn()
- circInOut()
- circOut()
- cubicIn()
- cubicInOut()
- cubicOut()
- elasticIn()
- elasticInOut()
- elasticOut()
- expoIn()
- expoInOut()
- expoOut()
- linear()
- quadIn()
- quadInOut()
- quadOut()
- quartIn()
- quartInOut()
- quartOut()
- quintIn()
- quintInOut()
- quintOut()
- sineIn()
- sineInOut()
- sineOut()
Functions
function $bindable
$bindable: typeof $bindable;
Declares a prop as bindable, meaning the parent component can use
bind:propName={value}
to bind to it.let { propName = $bindable() }: { propName: boolean } = $props();https://svelte.dev/docs/svelte/$bindable
function $derived
$derived: typeof $derived;
Declares derived state, i.e. one that depends on other state variables. The expression inside
$derived(...)
should be free of side-effects.Example:
let double = $derived(count * 2);https://svelte.dev/docs/svelte/$derived
Parameter expression
The derived state expression
function $effect
$effect: typeof $effect;
Runs code when a component is mounted to the DOM, and then whenever its dependencies change, i.e.
$state
or$derived
values. The timing of the execution is after the DOM has been updated.Example:
$effect(() => console.log('The count is now ' + count));If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server side rendering.
https://svelte.dev/docs/svelte/$effect
Parameter fn
The function to execute
function $host
$host: typeof $host;
Retrieves the
this
reference of the custom element that contains this component. Example:<svelte:options customElement="my-element" /><script>function greet(greeting) {$host().dispatchEvent(new CustomEvent('greeting', { detail: greeting }))}</script><button onclick={() => greet('hello')}>say hello</button>Only available inside custom element components, and only on the client-side.
https://svelte.dev/docs/svelte/$host
function $inspect
$inspect: typeof $inspect;
Inspects one or more values whenever they, or the properties they contain, change. Example:
$inspect(someValue, someOtherValue)$inspect
returns awith
function, which you can invoke with a callback function that will be called with the value and the event type ('init'
or'update'
) on every change. By default, the values will be logged to the console.$inspect(x).with(console.trace);$inspect(x, y).with(() => { debugger; });https://svelte.dev/docs/svelte/$inspect
function $props
$props: typeof $props;
Declares the props that a component accepts. Example:
let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();https://svelte.dev/docs/svelte/$props
function $state
$state: typeof $state;
Declares reactive state.
Example:
let count = $state(0);https://svelte.dev/docs/svelte/$state
Parameter initial
The initial value
Namespaces
namespace *.svelte
module '*.svelte' {}
namespace $bindable
namespace $bindable {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
namespace $derived
namespace $derived {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
function by
by: { <T>(fn: () => T): T; <T>(fn: () => T): T };
Sometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use
$derived.by
which accepts a function as its argument.Example:
let total = $derived.by(() => {let result = 0;for (const n of numbers) {result += n;}return result;});https://svelte.dev/docs/svelte/$derived#$derived.by
namespace $effect
namespace $effect {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
function pre
pre: { (fn: () => void | (() => void)): void; (fn: () => void | (() => void)): void;};
Runs code right before a component is mounted to the DOM, and then whenever its dependencies change, i.e.
$state
or$derived
values. The timing of the execution is right before the DOM is updated.Example:
$effect.pre(() => console.log('The count is now ' + count));If you return a function from the effect, it will be called right before the effect is run again, or when the component is unmounted.
Does not run during server side rendering.
https://svelte.dev/docs/svelte/$effect#$effect.pre
Parameter fn
The function to execute
function root
root: { (fn: () => void | (() => void)): () => void; (fn: () => void | (() => void)): () => void;};
The
$effect.root
rune is an advanced feature that creates a non-tracked scope that doesn't auto-cleanup. This is useful for nested effects that you want to manually control. This rune also allows for creation of effects outside of the component initialisation phase.Example:
<script>let count = $state(0);const cleanup = $effect.root(() => {$effect(() => {console.log(count);})return () => {console.log('effect root cleanup');}});</script><button onclick={() => cleanup()}>cleanup</button>https://svelte.dev/docs/svelte/$effect#$effect.root
function tracking
tracking: { (): boolean; (): boolean };
The
$effect.tracking
rune is an advanced feature that tells you whether or not the code is running inside a tracking context, such as an effect or inside your template.Example:
<script>console.log('in component setup:', $effect.tracking()); // false$effect(() => {console.log('in effect:', $effect.tracking()); // true});</script><p>in template: {$effect.tracking()}</p> <!-- true -->This allows you to (for example) add things like subscriptions without causing memory leaks, by putting them in child effects.
https://svelte.dev/docs/svelte/$effect#$effect.tracking
namespace $host
namespace $host {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
namespace $inspect
namespace $inspect {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
function trace
trace: { (name: string): void; (name: string): void };
Tracks which reactive state changes caused an effect to re-run. Must be the first statement of a function body. Example:
```svelte let count = $state(0);
$effect(() => { $inspect.trace('my effect');
count; });
namespace $props
namespace $props {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
namespace $state
namespace $state {}
variable apply
const apply: never;
Deprecated
variable arguments
const arguments: never;
Deprecated
variable bind
const bind: never;
Deprecated
variable call
const call: never;
Deprecated
variable caller
const caller: never;
Deprecated
variable length
const length: never;
Deprecated
variable name
const name: never;
Deprecated
variable prototype
const prototype: never;
Deprecated
variable toString
const toString: never;
Deprecated
function raw
raw: { <T>(initial: T): T; <T>(): T; <T>(initial: T): T; <T>(): T };
Declares state that is _not_ made deeply reactive — instead of mutating it, you must reassign it.
Example:
<script>let items = $state.raw([0]);const addItem = () => {items = [...items, items.length];};</script><button on:click={addItem}>{items.join(', ')}</button>https://svelte.dev/docs/svelte/$state#$state.raw
Parameter initial
The initial value
function snapshot
snapshot: { <T>(state: T): Snapshot<T>; <T>(state: T): Snapshot<T> };
To take a static snapshot of a deeply reactive
$state
proxy, use$state.snapshot
:Example:
<script>let counter = $state({ count: 0 });function onclick() {// Will log `{ count: ... }` rather than `Proxy { ... }`console.log($state.snapshot(counter));};</script>https://svelte.dev/docs/svelte/$state#$state.snapshot
Parameter state
The value to snapshot
type Cloneable
type Cloneable = | ArrayBuffer | DataView | Date | Error | Map<any, any> | RegExp | Set<any> | TypedArray // web APIs | Blob | CryptoKey | DOMException | DOMMatrix | DOMMatrixReadOnly | DOMPoint | DOMPointReadOnly | DOMQuad | DOMRect | DOMRectReadOnly | File | FileList | FileSystemDirectoryHandle | FileSystemFileHandle | FileSystemHandle | ImageBitmap | ImageData | RTCCertificate | VideoFrame;
The things that
structuredClone
can handle — https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
type NonReactive
type NonReactive<T> = T extends Date ? Date : T extends Map<infer K, infer V> ? Map<K, V> : T extends Set<infer K> ? Set<K> : T;
Turn
SvelteDate
,SvelteMap
andSvelteSet
into their non-reactive counterparts. (URL
is uncloneable.)
type Primitive
type Primitive = string | number | boolean | null | undefined;
type Snapshot
type Snapshot<T> = T extends Primitive ? T : T extends Cloneable ? NonReactive<T> : T extends { toJSON(): infer R } ? R : T extends Array<infer U> ? Array<Snapshot<U>> : T extends object ? T extends { [key: string]: any } ? { [K in keyof T]: Snapshot<T[K]> } : never : never;
type TypedArray
type TypedArray = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
namespace acorn-typescript
module 'acorn-typescript' {}
namespace svelte
module 'svelte' {}
function afterUpdate
afterUpdate: (fn: () => void) => void;
Schedules a callback to run immediately after the component has been updated.
The first time the callback runs will be after the initial
onMount
.In runes mode use
$effect
instead.Deprecated
Use [
$effect
](https://svelte.dev/docs/svelte/$effect) instead
function beforeUpdate
beforeUpdate: (fn: () => void) => void;
Schedules a callback to run immediately before the component is updated after any state change.
The first time the callback runs will be before the initial
onMount
.In runes mode use
$effect.pre
instead.Deprecated
Use [
$effect.pre
](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead
function createEventDispatcher
createEventDispatcher: < EventMap extends Record<string, any> = any>() => EventDispatcher<EventMap>;
Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events). Event dispatchers are functions that can take two arguments:
name
anddetail
.Component events created with
createEventDispatcher
create a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent). These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture). Thedetail
argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail) property and can contain any type of data.The event dispatcher can be typed to narrow the allowed event names and the type of the
detail
argument:const dispatch = createEventDispatcher<{loaded: never; // does not take a detail argumentchange: string; // takes a detail argument of type string, which is requiredoptional: number | null; // takes an optional detail argument of type number}>();Deprecated
Use callback props and/or the
$host()
rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events)
function createRawSnippet
createRawSnippet: <Params extends unknown[]>( fn: (...params: Getters<Params>) => { render: () => string; setup?: (element: Element) => void | (() => void); }) => Snippet<Params>;
Create a snippet programmatically
function flushSync
flushSync: (fn?: (() => void) | undefined) => void;
Synchronously flushes any pending state changes and those that result from it.
function getAllContexts
getAllContexts: <T extends Map<any, any> = Map<any, any>>() => T;
Retrieves 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.
function getContext
getContext: <T>(key: any) => T;
Retrieves the context that belongs to the closest parent component with the specified
key
. Must be called during component initialisation.
function hasContext
hasContext: (key: any) => boolean;
Checks whether a given
key
has been set in the context of a parent component. Must be called during component initialisation.
function hydrate
hydrate: < Props extends Record<string, any>, Exports extends Record<string, any>>( component: | ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: {} extends Props ? { target: Document | Element | ShadowRoot; props?: Props; events?: Record<string, (e: any) => any>; context?: Map<any, any>; intro?: boolean; recover?: boolean; } : { target: Document | Element | ShadowRoot; props: Props; events?: Record<string, (e: any) => any>; context?: Map<any, any>; intro?: boolean; recover?: boolean; }) => Exports;
Hydrates a component on the given target and returns the exports and potentially the props (if compiled with
accessors: true
) of the component
function mount
mount: <Props extends Record<string, any>, Exports extends Record<string, any>>( component: | ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>, options: MountOptions<Props>) => Exports;
Mounts a component to the given target and returns the exports and potentially the props (if compiled with
accessors: true
) of the component. Transitions will play during the initial render unless theintro
option is set tofalse
.
function onDestroy
onDestroy: (fn: () => any) => void;
Schedules a callback to run immediately before the component is unmounted.
Out of
onMount
,beforeUpdate
,afterUpdate
andonDestroy
, this is the only one that runs inside a server-side component.
function onMount
onMount: <T>( fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)) => void;
The
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).If a function is returned _synchronously_ from
onMount
, it will be called when the component is unmounted.onMount
does not run inside [server-side components](https://svelte.dev/docs/svelte/svelte-server#render).
function setContext
setContext: <T>(key: any, context: T) => T;
Associates an arbitrary
context
object with the current component and the specifiedkey
and returns that object. The context is then available to children of the component (including slotted content) withgetContext
.Like lifecycle functions, this must be called during component initialisation.
function tick
tick: () => Promise<void>;
Returns a promise that resolves once any pending state changes have been applied.
function unmount
unmount: ( component: Record<string, any>, options?: { outro?: boolean } | undefined) => Promise<void>;
Unmounts a component that was previously mounted using
mount
orhydrate
.Since 5.13.0, if
options.outro
istrue
, [transitions](https://svelte.dev/docs/svelte/transition) will play before the component is removed from the DOM.Returns a
Promise
that resolves after transitions have completed ifoptions.outro
is true, or immediately otherwise (prior to 5.13.0, returnsvoid
).import { mount, unmount } from 'svelte';import App from './App.svelte';const app = mount(App, { target: document.body });// later...unmount(app, { outro: true });
function untrack
untrack: <T>(fn: () => T) => T;
When used inside a [
$derived
](https://svelte.dev/docs/svelte/$derived) or [$effect
](https://svelte.dev/docs/svelte/$effect), any state read insidefn
will not be treated as a dependency.$effect(() => {// this will run when `data` changes, but not when `time` changessave(data, {timestamp: untrack(() => time)});});
class SvelteComponent
class SvelteComponent< Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> {}
This was the base class for Svelte components in Svelte 4. Svelte 5+ components are completely different under the hood. For typing, use
Component
instead. To instantiate components, usemount
instead. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
constructor
constructor(options: ComponentConstructorOptions<Properties<Props, Slots>>);
Deprecated
This constructor only exists when using the
asClassComponent
compatibility helper, which is a stop-gap solution. Migrate towards usingmount
instead. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
property $$bindings
$$bindings?: string;
For type checking capabilities only. Does not exist at runtime. ### DO NOT USE!
property $$events_def
$$events_def: Record<string, any>;
For type checking capabilities only. Does not exist at runtime. ### DO NOT USE!
property $$prop_def
$$prop_def: Record<string, any>;
For type checking capabilities only. Does not exist at runtime. ### DO NOT USE!
property $$slot_def
$$slot_def: Record<string, any>;
For type checking capabilities only. Does not exist at runtime. ### DO NOT USE!
property element
static element?: { new (): HTMLElement; prototype: HTMLElement };
The custom element version of the component. Only present if compiled with the
customElement
compiler option
method $destroy
$destroy: () => void;
Deprecated
This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
method $on
$on: <K extends Extract<keyof Events, string>>( type: K, callback: (e: Events[K]) => void) => () => void;
Deprecated
This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
method $set
$set: (props: Partial<Props>) => void;
Deprecated
This method only exists when using one of the legacy compatibility helpers, which is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
class SvelteComponentTyped
class SvelteComponentTyped< Props extends Record<string, any> = Record<string, any>, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> extends SvelteComponent<Props, Events, Slots> {}
Deprecated
Use
Component
instead. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more information.
interface Component
interface Component< Props extends Record<string, any> = {}, Exports extends Record<string, any> = {}, Bindings extends keyof Props | '' = string> {}
Can be used to create strongly typed Svelte components.
#### Example:
You have component library on npm called
component-library
, from which you export a component calledMyComponent
. For Svelte+TypeScript users, you want to provide typings. Therefore you create aindex.d.ts
:import type { Component } from 'svelte';export declare const MyComponent: Component<{ foo: string }> {}Typing this makes it possible for IDEs like VS Code with the Svelte extension to provide intellisense and to use the component like this in a Svelte file with TypeScript:
<script lang="ts">import { MyComponent } from "component-library";</script><MyComponent foo={'bar'} />
property element
element?: typeof HTMLElement;
The custom element version of the component. Only present if compiled with the
customElement
compiler option
property z_$$bindings
z_$$bindings?: Bindings;
Does not exist at runtime, for typing capabilities only. DO NOT USE
call signature
(this: void, internals: ComponentInternals, props: Props): { /** * @deprecated This method only exists when using one of the legacy compatibility helpers, which * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) * for more info. */ $on?(type: string, callback: (e: any) => void): () => void; /** * @deprecated This method only exists when using one of the legacy compatibility helpers, which * is a stop-gap solution. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) * for more info. */ $set?(props: Partial<Props>): void;} & Exports;
Parameter internal
An internal object used by Svelte. Do not use or modify.
Parameter props
The props passed to the component.
interface ComponentConstructorOptions
interface ComponentConstructorOptions< Props extends Record<string, any> = Record<string, any>> {}
Deprecated
In Svelte 4, components are classes. In Svelte 5, they are functions. Use
mount
instead to instantiate components. See [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Components-are-no-longer-classes) for more info.
property $$inline
$$inline?: boolean;
property anchor
anchor?: Element;
property context
context?: Map<any, any>;
property hydrate
hydrate?: boolean;
property intro
intro?: boolean;
property props
props?: Props;
property recover
recover?: boolean;
property sync
sync?: boolean;
property target
target: Element | Document | ShadowRoot;
interface EventDispatcher
interface EventDispatcher<EventMap extends Record<string, any>> {}
call signature
<Type extends keyof EventMap>( ...args: null extends EventMap[Type] ? [ type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions ] : undefined extends EventMap[Type] ? [ type: Type, parameter?: EventMap[Type] | null | undefined, options?: DispatchOptions ] : [type: Type, parameter: EventMap[Type], options?: DispatchOptions]): boolean;
interface Snippet
interface Snippet<Parameters extends unknown[] = []> {}
The type of a
#snippet
block. You can use it to (for example) express that your component expects a snippet of a certain type:let { banner }: { banner: Snippet<[{ text: string }]> } = $props();You can only call a snippet through the
{@render ...}
tag.https://svelte.dev/docs/svelte/snippet
Parameters the parameters that the snippet expects (if any) as a tuple.
call signature
( this: void, // this conditional allows tuples but not arrays. Arrays would indicate a // rest parameter type, which is not supported. If rest parameters are added // in the future, the condition can be removed. ...args: number extends Parameters['length'] ? never : Parameters): { '{@render ...} must be called with a Snippet': "import type { Snippet } from 'svelte'";} & typeof SnippetReturn;
type ComponentEvents
type ComponentEvents<Comp extends SvelteComponent> = Comp extends SvelteComponent< any, infer Events> ? Events : never;
Deprecated
The new
Component
type does not have a dedicated Events type. UseComponentProps
instead.Convenience type to get the events the given component expects. Example:
<script lang="ts">import type { ComponentEvents } from 'svelte';import Component from './Component.svelte';function handleCloseEvent(event: ComponentEvents<Component>['close']) {console.log(event.detail);}</script><Component on:close={handleCloseEvent} />
type ComponentInternals
type ComponentInternals = Branded<{}, 'ComponentInternals'>;
Internal implementation details that vary between environments
type ComponentProps
type ComponentProps<Comp extends SvelteComponent | Component<any, any>> = Comp extends SvelteComponent<infer Props> ? Props : Comp extends Component<infer Props, any> ? Props : never;
Convenience type to get the props the given component expects.
Example: Ensure a variable contains the props expected by
MyComponent
:import type { ComponentProps } from 'svelte';import MyComponent from './MyComponent.svelte';// Errors if these aren't the correct props expected by MyComponent.const props: ComponentProps<typeof MyComponent> = { foo: 'bar' };> [!NOTE] In Svelte 4, you would do
ComponentProps<MyComponent>
becauseMyComponent
was a class.Example: A generic function that accepts some component and infers the type of its props:
import type { Component, ComponentProps } from 'svelte';import MyComponent from './MyComponent.svelte';function withProps<TComponent extends Component<any>>(component: TComponent,props: ComponentProps<TComponent>) {};// Errors if the second argument is not the correct props expected by the component in the first argument.withProps(MyComponent, { foo: 'bar' });
type ComponentType
type ComponentType<Comp extends SvelteComponent = SvelteComponent> = (new ( options: ComponentConstructorOptions< Comp extends SvelteComponent<infer Props> ? Props : Record<string, any> >) => Comp) & { /** The custom element version of the component. Only present if compiled with the `customElement` compiler option */ element?: typeof HTMLElement;};
Deprecated
This type is obsolete when working with the new
Component
type.Convenience type to get the type of a Svelte component. Useful for example in combination with dynamic components using
<svelte:component>
.Example:
<script lang="ts">import type { ComponentType, SvelteComponent } from 'svelte';import Component1 from './Component1.svelte';import Component2 from './Component2.svelte';const component: ComponentType = someLogic() ? Component1 : Component2;const componentOfCertainSubType: ComponentType<SvelteComponent<{ needsThisProp: string }>> = someLogic() ? Component1 : Component2;</script><svelte:component this={component} /><svelte:component this={componentOfCertainSubType} needsThisProp="hello" />
type MountOptions
type MountOptions<Props extends Record<string, any> = Record<string, any>> = { /** * Target element where the component will be mounted. */ target: Document | Element | ShadowRoot; /** * Optional node inside `target`. When specified, it is used to render the component immediately before it. */ anchor?: Node; /** * Allows the specification of events. * @deprecated Use callback props instead. */ events?: Record<string, (e: any) => any>; /** * Can be accessed via `getContext()` at the component level. */ context?: Map<any, any>; /** * Whether or not to play transitions on initial render. * @default true */ intro?: boolean;} & ({} extends Props ? { /** * Component properties. */ props?: Props; } : { /** * Component properties. */ props: Props; });
Defines the options accepted by the
mount()
function.
namespace svelte/action
module 'svelte/action' {}
interface Action
interface Action< Element = HTMLElement, Parameter = undefined, Attributes extends Record<string, any> = Record<never, any>> {}
Actions are functions that are called when an element is created. You can use this interface to type such actions. The following example defines an action that only works on
<div>
elements and optionally accepts a parameter which it has a default value for:export const myAction: Action<HTMLDivElement, { someProperty: boolean } | undefined> = (node, param = { someProperty: true }) => {// ...}Action<HTMLDivElement>
andAction<HTMLDivElement, undefined>
both signal that the action accepts no parameters.You can return an object with methods
update
anddestroy
from the function and type which additional attributes and events it has. See interfaceActionReturn
for more details.
call signature
<Node extends Element>( ...args: undefined extends Parameter ? [node: Node, parameter?: Parameter] : [node: Node, parameter: Parameter]): void | ActionReturn<Parameter, Attributes>;
interface ActionReturn
interface ActionReturn< Parameter = undefined, Attributes extends Record<string, any> = Record<never, any>> {}
Actions can return an object containing the two properties defined in this interface. Both are optional. - update: An action can have a parameter. This method will be called whenever that parameter changes, immediately after Svelte has applied updates to the markup.
ActionReturn
andActionReturn<undefined>
both mean that the action accepts no parameters. - destroy: Method that is called after the element is unmountedAdditionally, you can specify which additional attributes and events the action enables on the applied element. This applies to TypeScript typings only and has no effect at runtime.
Example usage:
interface Attributes {newprop?: string;'on:event': (e: CustomEvent<boolean>) => void;}export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {// ...return {update: (updatedParameter) => {...},destroy: () => {...}};}
property $$_attributes
$$_attributes?: Attributes;
### DO NOT USE THIS This exists solely for type-checking and has no effect at runtime. Set this through the
Attributes
generic instead.
property destroy
destroy?: () => void;
property update
update?: (parameter: Parameter) => void;
namespace svelte/animate
module 'svelte/animate' {}
function flip
flip: ( node: Element, { from, to }: { from: DOMRect; to: DOMRect }, params?: FlipParams) => AnimationConfig;
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](https://aerotwist.com/blog/flip-your-animations/).
interface AnimationConfig
interface AnimationConfig {}
interface FlipParams
interface FlipParams {}
namespace svelte/compiler
module 'svelte/compiler' {}
variable VERSION
const VERSION: string;
The current version, as set in package.json.
https://svelte.dev/docs/svelte-compiler#svelte-version
function compile
compile: (source: string, options: CompileOptions) => CompileResult;
compile
converts your.svelte
source code into a JavaScript module that exports a componentParameter source
The component source code
Parameter options
The compiler options
function compileModule
compileModule: (source: string, options: ModuleCompileOptions) => CompileResult;
compileModule
takes your JavaScript source code containing runes, and turns it into a JavaScript module.Parameter source
The component source code
function migrate
migrate: ( source: string, { filename, use_ts }?: { filename?: string; use_ts?: boolean } | undefined) => { code: string };
Does a best-effort migration of Svelte code towards using runes, event attributes and render tags. May throw an error if the code is too complex to migrate automatically.
function parse
parse: { ( source: string, options: { filename?: string; modern: true; loose?: boolean } ): AST.Root; ( source: string, options?: { filename?: string; modern?: false; loose?: boolean } ): Record<string, any>;};
The parse function parses a component, returning only its abstract syntax tree.
The
modern
option (false
by default in Svelte 5) makes the parser return a modern AST instead of the legacy AST.modern
will becometrue
by default in Svelte 6, and the option will be removed in Svelte 7.
function preprocess
preprocess: ( source: string, preprocessor: PreprocessorGroup | PreprocessorGroup[], options?: { filename?: string } | undefined) => Promise<Processed>;
The preprocess function provides convenient hooks for arbitrarily transforming component source code. For example, it can be used to convert a
<style lang="sass">
block into vanilla CSS.
function walk
walk: () => never;
Deprecated
Replace this with
import { walk } from 'estree-walker'
interface CompileError
interface CompileError extends ICompileDiagnostic {}
interface CompileOptions
interface CompileOptions extends ModuleCompileOptions {}
property accessors
accessors?: boolean;
If
true
, getters and setters will be created for the component's props. Iffalse
, they will only be created for readonly exported values (i.e. those declared withconst
,class
andfunction
). If compiling withcustomElement: true
this option defaults totrue
.false
Deprecated
This will have no effect in runes mode
property compatibility
compatibility?: { /** * Applies a transformation so that the default export of Svelte files can still be instantiated the same way as in Svelte 4 — * as a class when compiling for the browser (as though using `createClassComponent(MyComponent, {...})` from `svelte/legacy`) * or as an object with a `.render(...)` method when compiling for the server * @default 5 */ componentApi?: 4 | 5;};
Deprecated
Use these only as a temporary solution before migrating your code
property css
css?: 'injected' | 'external';
-
'injected'
: styles will be included in thehead
when usingrender(...)
, and injected into the document (if not already present) when the component mounts. For components compiled as custom elements, styles are injected to the shadow root. -'external'
: the CSS will only be returned in thecss
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. This is always'injected'
when compiling withcustomElement
mode.
property cssHash
cssHash?: CssHashGetter;
A function that takes a
{ hash, css, name, filename }
argument and returns the string that is used as a classname for scoped CSS. It defaults to returningsvelte-${hash(css)}
.undefined
property cssOutputFilename
cssOutputFilename?: string;
Used for your CSS sourcemap.
null
property customElement
customElement?: boolean;
If
true
, tells the compiler to generate a custom element constructor instead of a regular Svelte component.false
property discloseVersion
discloseVersion?: boolean;
If
true
, exposes the Svelte major version in the browser by adding it to aSet
stored in the globalwindow.__svelte.v
.true
property hmr
hmr?: boolean;
If
true
, compiles components with hot reloading support.false
property immutable
immutable?: boolean;
If
true
, tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed.false
Deprecated
This will have no effect in runes mode
property modernAst
modernAst?: boolean;
If
true
, returns the modern version of the AST. Will becometrue
by default in Svelte 6, and the option will be removed in Svelte 7.false
property name
name?: string;
Sets the name of the resulting JavaScript class (though the compiler will rename it if it would otherwise conflict with other variables in scope). If unspecified, will be inferred from
filename
property namespace
namespace?: Namespace;
The namespace of the element; e.g.,
"html"
,"svg"
,"mathml"
.'html'
property outputFilename
outputFilename?: string;
Used for your JavaScript sourcemap.
null
property preserveComments
preserveComments?: boolean;
If
true
, your HTML comments will be preserved in the output. By default, they are stripped out.false
property preserveWhitespace
preserveWhitespace?: boolean;
If
true
, whitespace inside and between elements is kept as you typed it, rather than removed or collapsed to a single space where possible.false
property runes
runes?: boolean | undefined;
Set to
true
to force the compiler into runes mode, even if there are no indications of runes usage. Set tofalse
to force the compiler into ignoring runes, even if there are indications of runes usage. Set toundefined
(the default) to infer runes mode from the component code. Is alwaystrue
for JS/TS modules compiled with Svelte. Will betrue
by default in Svelte 6. Note that setting this totrue
in yoursvelte.config.js
will force runes mode for your entire project, including components innode_modules
, which is likely not what you want. If you're using Vite, consider using [dynamicCompileOptions](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#dynamiccompileoptions) instead. undefined
property sourcemap
sourcemap?: object | string;
An initial sourcemap that will be merged into the final output sourcemap. This is usually the preprocessor sourcemap.
null
interface CompileResult
interface CompileResult {}
The return value of
compile
fromsvelte/compiler
property ast
ast: any;
The AST
property css
css: null | { /** The generated code */ code: string; /** A source map */ map: SourceMap;};
The compiled CSS
property js
js: { /** The generated code */ code: string; /** A source map */ map: SourceMap;};
The compiled JavaScript
property metadata
metadata: { /** * Whether the file was compiled in runes mode, either because of an explicit option or inferred from usage. * For `compileModule`, this is always `true` */ runes: boolean;};
Metadata about the compiled component
property warnings
warnings: Warning[];
An array of warning objects that were generated during compilation. Each warning has several properties: -
code
is a string identifying the category of warning -message
describes the issue in human-readable terms -start
andend
, if the warning relates to a specific location, are objects withline
,column
andcharacter
properties
interface ModuleCompileOptions
interface ModuleCompileOptions {}
property dev
dev?: boolean;
If
true
, causes extra code to be added that will perform runtime checks and provide debugging information during development.false
property filename
filename?: string;
Used for debugging hints and sourcemaps. Your bundler plugin will set it automatically.
property generate
generate?: 'client' | 'server' | false;
If
"client"
, Svelte emits code designed to run in the browser. If"server"
, Svelte emits code suitable for server-side rendering. Iffalse
, nothing is generated. Useful for tooling that is only interested in warnings.'client'
property rootDir
rootDir?: string;
Used for ensuring filenames don't leak filesystem information. Your bundler plugin will set it automatically. process.cwd() on node-like environments, undefined elsewhere
property warningFilter
warningFilter?: (warning: Warning) => boolean;
A function that gets a
Warning
as an argument and returns a boolean. Use this to filter out warnings. Returntrue
to keep the warning,false
to discard it.
interface PreprocessorGroup
interface PreprocessorGroup {}
A preprocessor group is a set of preprocessors that are applied to a Svelte file.
interface Processed
interface Processed {}
The result of a preprocessor run. If the preprocessor does not return a result, it is assumed that the code is unchanged.
property attributes
attributes?: Record<string, string | boolean>;
Only for script/style preprocessors: The updated attributes to set on the tag. If undefined, attributes stay unchanged.
property code
code: string;
The new code
property dependencies
dependencies?: string[];
A list of additional files to watch for changes
property map
map?: string | object;
A source map mapping back to the original code
property toString
toString?: () => string;
interface Warning
interface Warning extends ICompileDiagnostic {}
type MarkupPreprocessor
type MarkupPreprocessor = (options: { /** * The whole Svelte file content */ content: string; /** * The filename of the Svelte file */ filename?: string;}) => Processed | void | Promise<Processed | void>;
A markup preprocessor that takes a string of code and returns a processed version.
type Preprocessor
type Preprocessor = (options: { /** * The script/style tag content */ content: string; /** * The attributes on the script/style tag */ attributes: Record<string, string | boolean>; /** * The whole Svelte file content */ markup: string; /** * The filename of the Svelte file */ filename?: string;}) => Processed | void | Promise<Processed | void>;
A script/style preprocessor that takes a string of code and returns a processed version.
namespace svelte/compiler.AST
namespace svelte/compiler.AST {}
interface AnimateDirective
interface AnimateDirective extends BaseNode {}
An
animate:
directive
property expression
expression: null | Expression;
The y in
animate:x={y}
property name
name: string;
The 'x' in
animate:x
property type
type: 'AnimateDirective';
interface Attribute
interface Attribute extends BaseNode {}
interface AwaitBlock
interface AwaitBlock extends BaseNode {}
An
{#await ...}
block
property catch
catch: Fragment | null;
property error
error: Pattern | null;
The rejection reason inside the
catch
block
property expression
expression: Expression;
property pending
pending: Fragment | null;
property then
then: Fragment | null;
property type
type: 'AwaitBlock';
property value
value: Pattern | null;
The resolved value inside the
then
block
interface BaseNode
interface BaseNode {}
interface BindDirective
interface BindDirective extends BaseNode {}
A
bind:
directive
property expression
expression: Identifier | MemberExpression | SequenceExpression;
The y in
bind:x={y}
property name
name: string;
The 'x' in
bind:x
property type
type: 'BindDirective';
interface ClassDirective
interface ClassDirective extends BaseNode {}
A
class:
directive
property expression
expression: Expression;
The 'y' in
class:x={y}
, or thex
inclass:x
property name
name: 'class';
The 'x' in
class:x
property type
type: 'ClassDirective';
interface Comment
interface Comment extends BaseNode {}
An HTML comment
interface ConstTag
interface ConstTag extends BaseNode {}
A
{@const ...}
tag
property declaration
declaration: VariableDeclaration & { declarations: [VariableDeclarator & { id: Pattern; init: Expression }];};
property type
type: 'ConstTag';
interface DebugTag
interface DebugTag extends BaseNode {}
A
{@debug ...}
tag
property identifiers
identifiers: Identifier[];
property type
type: 'DebugTag';
interface EachBlock
interface EachBlock extends BaseNode {}
An
{#each ...}
block
interface ExpressionTag
interface ExpressionTag extends BaseNode {}
A (possibly reactive) template expression —
{...}
property expression
expression: Expression;
property type
type: 'ExpressionTag';
interface Fragment
interface Fragment {}
interface HtmlTag
interface HtmlTag extends BaseNode {}
A (possibly reactive) HTML template expression —
{@html ...}
property expression
expression: Expression;
property type
type: 'HtmlTag';
interface IfBlock
interface IfBlock extends BaseNode {}
An
{#if ...}
block
property alternate
alternate: Fragment | null;
property consequent
consequent: Fragment;
property elseif
elseif: boolean;
property test
test: Expression;
property type
type: 'IfBlock';
interface KeyBlock
interface KeyBlock extends BaseNode {}
property expression
expression: Expression;
property fragment
fragment: Fragment;
property type
type: 'KeyBlock';
interface LetDirective
interface LetDirective extends BaseNode {}
A
let:
directive
property expression
expression: null | Identifier | ArrayExpression | ObjectExpression;
The 'y' in
let:x={y}
property name
name: string;
The 'x' in
let:x
property type
type: 'LetDirective';
interface OnDirective
interface OnDirective extends BaseNode {}
An
on:
directive
property expression
expression: null | Expression;
The 'y' in
on:x={y}
property modifiers
modifiers: string[];
property name
name: string;
The 'x' in
on:x
property type
type: 'OnDirective';
interface RegularElement
interface RegularElement extends BaseElement {}
property type
type: 'RegularElement';
interface RenderTag
interface RenderTag extends BaseNode {}
A ` tag
property expression
expression: | SimpleCallExpression | (ChainExpression & { expression: SimpleCallExpression });
property type
type: 'RenderTag';
interface Root
interface Root extends BaseNode {}
property css
css: AST.CSS.StyleSheet | null;
The parsed
<style>
element, if exists
property fragment
fragment: Fragment;
property instance
instance: Script | null;
The parsed
<script>
element, if exists
property module
module: Script | null;
The parsed
<script module>
element, if exists
property options
options: SvelteOptions | null;
Inline options provided by
<svelte:options>
— these override options passed tocompile(...)
property type
type: 'Root';
interface Script
interface Script extends BaseNode {}
property attributes
attributes: Attribute[];
property content
content: Program;
property context
context: 'default' | 'module';
property type
type: 'Script';
interface SlotElement
interface SlotElement extends BaseElement {}
interface SnippetBlock
interface SnippetBlock extends BaseNode {}
property body
body: Fragment;
property expression
expression: Identifier;
property parameters
parameters: Pattern[];
property type
type: 'SnippetBlock';
interface SpreadAttribute
interface SpreadAttribute extends BaseNode {}
property expression
expression: Expression;
property type
type: 'SpreadAttribute';
interface StyleDirective
interface StyleDirective extends BaseNode {}
A
style:
directive
interface SvelteBody
interface SvelteBody extends BaseElement {}
interface SvelteBoundary
interface SvelteBoundary extends BaseElement {}
interface SvelteComponent
interface SvelteComponent extends BaseElement {}
property expression
expression: Expression;
property name
name: 'svelte:component';
property type
type: 'SvelteComponent';
interface SvelteDocument
interface SvelteDocument extends BaseElement {}
interface SvelteElement
interface SvelteElement extends BaseElement {}
interface SvelteFragment
interface SvelteFragment extends BaseElement {}
interface SvelteHead
interface SvelteHead extends BaseElement {}
interface SvelteOptions
interface SvelteOptions {}
property accessors
accessors?: boolean;
property attributes
attributes: Attribute[];
property css
css?: 'injected';
property customElement
customElement?: { tag?: string; shadow?: 'open' | 'none'; props?: Record< string, { attribute?: string; reflect?: boolean; type?: 'Array' | 'Boolean' | 'Number' | 'Object' | 'String'; } >; /** * Is of type * ```ts * (ceClass: new () => HTMLElement) => new () => HTMLElement * ``` */ extend?: ArrowFunctionExpression | Identifier;};
property end
end: number;
property immutable
immutable?: boolean;
property namespace
namespace?: Namespace;
property preserveWhitespace
preserveWhitespace?: boolean;
property runes
runes?: boolean;
property start
start: number;
interface SvelteOptionsRaw
interface SvelteOptionsRaw extends BaseElement {}
This is only an intermediate representation while parsing, it doesn't exist in the final AST
interface SvelteSelf
interface SvelteSelf extends BaseElement {}
interface SvelteWindow
interface SvelteWindow extends BaseElement {}
interface Text
interface Text extends BaseNode {}
Static text
interface TitleElement
interface TitleElement extends BaseElement {}
interface TransitionDirective
interface TransitionDirective extends BaseNode {}
A
transition:
,in:
orout:
directive
property expression
expression: null | Expression;
The 'y' in
transition:x={y}
property intro
intro: boolean;
True if this is a
transition:
orin:
directive
property modifiers
modifiers: Array<'local' | 'global'>;
property name
name: string;
The 'x' in
transition:x
property outro
outro: boolean;
True if this is a
transition:
orout:
directive
property type
type: 'TransitionDirective';
interface UseDirective
interface UseDirective extends BaseNode {}
A
use:
directive
property expression
expression: null | Expression;
The 'y' in
use:x={y}
property name
name: string;
The 'x' in
use:x
property type
type: 'UseDirective';
type AttributeLike
type AttributeLike = Attribute | SpreadAttribute | Directive;
type Block
type Block = | AST.EachBlock | AST.IfBlock | AST.AwaitBlock | AST.KeyBlock | AST.SnippetBlock;
type Directive
type Directive = | AST.AnimateDirective | AST.BindDirective | AST.ClassDirective | AST.LetDirective | AST.OnDirective | AST.StyleDirective | AST.TransitionDirective | AST.UseDirective;
type ElementLike
type ElementLike = | AST.Component | AST.TitleElement | AST.SlotElement | AST.RegularElement | AST.SvelteBody | AST.SvelteBoundary | AST.SvelteComponent | AST.SvelteDocument | AST.SvelteElement | AST.SvelteFragment | AST.SvelteHead | AST.SvelteOptionsRaw | AST.SvelteSelf | AST.SvelteWindow | AST.SvelteBoundary;
type SvelteNode
type SvelteNode = Node | TemplateNode | AST.Fragment | _CSS.Node;
type Tag
type Tag = | AST.ExpressionTag | AST.HtmlTag | AST.ConstTag | AST.DebugTag | AST.RenderTag;
type TemplateNode
type TemplateNode = | AST.Root | AST.Text | Tag | ElementLike | AST.Attribute | AST.SpreadAttribute | Directive | AST.Comment | Block;
namespace svelte/compiler.AST.CSS
namespace svelte/compiler.AST.CSS {}
interface Atrule
interface Atrule extends BaseNode {}
interface AttributeSelector
interface AttributeSelector extends BaseNode {}
interface Block
interface Block extends BaseNode {}
interface ClassSelector
interface ClassSelector extends BaseNode {}
interface Combinator
interface Combinator extends BaseNode {}
interface ComplexSelector
interface ComplexSelector extends BaseNode {}
A complex selector, e.g.
a b c {}
interface Declaration
interface Declaration extends BaseNode {}
interface IdSelector
interface IdSelector extends BaseNode {}
interface NestingSelector
interface NestingSelector extends BaseNode {}
interface Percentage
interface Percentage extends BaseNode {}
interface PseudoClassSelector
interface PseudoClassSelector extends BaseNode {}
interface PseudoElementSelector
interface PseudoElementSelector extends BaseNode {}
interface RelativeSelector
interface RelativeSelector extends BaseNode {}
A relative selector, e.g the
a
and> b
ina > b {}
property combinator
combinator: null | Combinator;
In
a > b
,> b
forms one relative selector, and>
is the combinator.null
for the first selector.
property selectors
selectors: SimpleSelector[];
The
b:is(...)
in> b:is(...)
property type
type: 'RelativeSelector';
interface Rule
interface Rule extends BaseNode {}
interface SelectorList
interface SelectorList extends BaseNode {}
A list of selectors, e.g.
a, b, c {}
interface StyleSheet
interface StyleSheet extends BaseNode {}
property attributes
attributes: any[];
property children
children: Array<Atrule | Rule>;
property content
content: { start: number; end: number; styles: string; /** Possible comment atop the style tag */ comment: AST.Comment | null;};
property type
type: 'StyleSheet';
interface TypeSelector
interface TypeSelector extends BaseNode {}
type Node
type Node = | StyleSheet | Rule | Atrule | SelectorList | Block | ComplexSelector | RelativeSelector | Combinator | SimpleSelector | Declaration;
type SimpleSelector
type SimpleSelector = | TypeSelector | IdSelector | ClassSelector | AttributeSelector | PseudoElementSelector | PseudoClassSelector | Percentage | Nth | NestingSelector;
namespace svelte/easing
module 'svelte/easing' {}
function backIn
backIn: (t: number) => number;
function backInOut
backInOut: (t: number) => number;
function backOut
backOut: (t: number) => number;
function bounceIn
bounceIn: (t: number) => number;
function bounceInOut
bounceInOut: (t: number) => number;
function bounceOut
bounceOut: (t: number) => number;
function circIn
circIn: (t: number) => number;
function circInOut
circInOut: (t: number) => number;
function circOut
circOut: (t: number) => number;
function cubicIn
cubicIn: (t: number) => number;
function cubicInOut
cubicInOut: (t: number) => number;
function cubicOut
cubicOut: (t: number) => number;
function elasticIn
elasticIn: (t: number) => number;
function elasticInOut
elasticInOut: (t: number) => number;
function elasticOut
elasticOut: (t: number) => number;
function expoIn
expoIn: (t: number) => number;
function expoInOut
expoInOut: (t: number) => number;
function expoOut
expoOut: (t: number) => number;
function linear
linear: (t: number) => number;
function quadIn
quadIn: (t: number) => number;
function quadInOut
quadInOut: (t: number) => number;
function quadOut
quadOut: (t: number) => number;
function quartIn
quartIn: (t: number) => number;
function quartInOut
quartInOut: (t: number) => number;
function quartOut
quartOut: (t: number) => number;
function quintIn
quintIn: (t: number) => number;
function quintInOut
quintInOut: (t: number) => number;
function quintOut
quintOut: (t: number) => number;
function sineIn
sineIn: (t: number) => number;
function sineInOut
sineInOut: (t: number) => number;
function sineOut
sineOut: (t: number) => number;
namespace svelte/events
module 'svelte/events' {}
function on
on: { <Type extends keyof WindowEventMap>( window: Window, type: Type, handler: (this: Window, event: WindowEventMap[Type]) => any, options?: AddEventListenerOptions | undefined ): () => void; <Type extends keyof DocumentEventMap>( document: Document, type: Type, handler: (this: Document, event: DocumentEventMap[Type]) => any, options?: AddEventListenerOptions ): () => void; <Element extends HTMLElement, Type extends keyof HTMLElementEventMap>( element: Element, type: Type, handler: (this: Element, event: HTMLElementEventMap[Type]) => any, options?: AddEventListenerOptions ): () => void; <Element extends MediaQueryList, Type extends 'change'>( element: Element, type: Type, handler: (this: Element, event: MediaQueryListEventMap[Type]) => any, options?: AddEventListenerOptions ): () => void; ( element: EventTarget, type: string, handler: EventListener, options?: AddEventListenerOptions ): () => void;};
Attaches an event handler to the window and returns a function that removes the handler. Using this rather than
addEventListener
will preserve the correct order relative to handlers added declaratively (with attributes likeonclick
), which use event delegation for performance reasonsAttaches an event handler to the document and returns a function that removes the handler. Using this rather than
addEventListener
will preserve the correct order relative to handlers added declaratively (with attributes likeonclick
), which use event delegation for performance reasonsAttaches an event handler to an element and returns a function that removes the handler. Using this rather than
addEventListener
will preserve the correct order relative to handlers added declaratively (with attributes likeonclick
), which use event delegation for performance reasons
namespace svelte/legacy
module 'svelte/legacy' {}
function asClassComponent
asClassComponent: < Props extends Record<string, any>, Exports extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>>( component: SvelteComponent<Props, Events, Slots> | Component<Props>) => ComponentType<SvelteComponent<Props, Events, Slots> & Exports>;
Takes the component function and returns a Svelte 4 compatible component constructor.
Deprecated
Use this only as a temporary solution to migrate your imperative component code to Svelte 5.
function createBubbler
createBubbler: () => (type: string) => (event: Event) => boolean;
Function to create a
bubble
function that mimic the behavior ofon:click
without handler available in svelte 4.Deprecated
Use this only as a temporary solution to migrate your automatically delegated events in Svelte 5.
function createClassComponent
createClassComponent: < Props extends Record<string, any>, Exports extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>>( options: ComponentConstructorOptions<Props> & { component: | ComponentType<SvelteComponent<Props, Events, Slots>> | Component<Props>; }) => SvelteComponent<Props, Events, Slots> & Exports;
Takes the same options as a Svelte 4 component and the component function and returns a Svelte 4 compatible component.
Deprecated
Use this only as a temporary solution to migrate your imperative component code to Svelte 5.
function handlers
handlers: (...handlers: EventListener[]) => EventListener;
Function to mimic the multiple listeners available in svelte 4
Deprecated
function nonpassive
nonpassive: ( node: HTMLElement, [event, handler]: [event: string, handler: () => EventListener]) => void;
Substitute for the
nonpassive
event modifier, implemented as an actionDeprecated
function once
once: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
once
event modifierDeprecated
function passive
passive: ( node: HTMLElement, [event, handler]: [event: string, handler: () => EventListener]) => void;
Substitute for the
passive
event modifier, implemented as an actionDeprecated
function preventDefault
preventDefault: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
preventDefault
event modifierDeprecated
function run
run: (fn: () => void | (() => void)) => void;
Runs the given function once immediately on the server, and works like
$effect.pre
on the client.Deprecated
Use this only as a temporary solution to migrate your component code to Svelte 5.
function self
self: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
self
event modifierDeprecated
function stopImmediatePropagation
stopImmediatePropagation: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
stopImmediatePropagation
event modifierDeprecated
function stopPropagation
stopPropagation: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
stopPropagation
event modifierDeprecated
function trusted
trusted: ( fn: (event: Event, ...args: Array<unknown>) => void) => (event: Event, ...args: unknown[]) => void;
Substitute for the
trusted
event modifierDeprecated
type LegacyComponentType
type LegacyComponentType = { new (o: ComponentConstructorOptions): SvelteComponent; (...args: Parameters<Component<Record<string, any>>>): ReturnType< Component<Record<string, any>, Record<string, any>> >;};
Support using the component as both a class and function during the transition period
namespace svelte/motion
module 'svelte/motion' {}
variable prefersReducedMotion
const prefersReducedMotion: MediaQuery;
A [media query](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery) that matches if the user [prefers reduced motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion).
<script>import { prefersReducedMotion } from 'svelte/motion';import { fly } from 'svelte/transition';let visible = $state(false);</script><button onclick={() => visible = !visible}>toggle</button>{#if visible}<p transition:fly={{ y: prefersReducedMotion.current ? 0 : 200 }}>flies in, unless the user prefers reduced motion</p>{/if}5.7.0
function spring
spring: <T = any>( value?: T | undefined, opts?: SpringOpts | undefined) => Spring<T>;
The spring function in Svelte creates a store whose value is animated, with a motion that simulates the behavior of a spring. This means when the value changes, instead of transitioning at a steady rate, it "bounces" like a spring would, depending on the physics parameters provided. This adds a level of realism to the transitions and can enhance the user experience.
Deprecated
Use [
Spring
](https://svelte.dev/docs/svelte/svelte-motion#Spring) instead
function tweened
tweened: <T>( value?: T | undefined, defaults?: TweenedOptions<T> | undefined) => Tweened<T>;
A tweened store in Svelte is a special type of store that provides smooth transitions between state values over time.
Deprecated
Use [
Tween
](https://svelte.dev/docs/svelte/svelte-motion#Tween) instead
class Spring
class Spring<T> {}
A wrapper for a value that behaves in a spring-like fashion. Changes to
spring.target
will causespring.current
to move towards it over time, taking account of thespring.stiffness
andspring.damping
parameters.<script>import { Spring } from 'svelte/motion';const spring = new Spring(0);</script><input type="range" bind:value={spring.target} /><input type="range" bind:value={spring.current} disabled />5.8.0
constructor
constructor(value: {}, options?: SpringOpts);
property current
readonly current: {};
The current value of the spring. This property only exists on the
Spring
class, not the legacyspring
store.
property damping
damping: number;
property precision
precision: number;
property stiffness
stiffness: number;
property target
target: {};
The end value of the spring. This property only exists on the
Spring
class, not the legacyspring
store.
method of
static of: <U>(fn: () => U, options?: SpringOpts) => Spring<U>;
Create a spring whose value is bound to the return value of
fn
. This must be called inside an effect root (for example, during component initialisation).<script>import { Spring } from 'svelte/motion';let { number } = $props();const spring = Spring.of(() => number);</script>
method set
set: { (new_value: T, opts?: SpringUpdateOpts): Promise<void>; (value: T, options?: SpringUpdateOpts): Promise<void>;};
Sets
spring.target
tovalue
and returns aPromise
that resolves if and whenspring.current
catches up to it.If
options.instant
istrue
,spring.current
immediately matchesspring.target
.If
options.preserveMomentum
is provided, the spring will continue on its current trajectory for the specified number of milliseconds. This is useful for things like 'fling' gestures.
class Tween
class Tween<T> {}
A wrapper for a value that tweens smoothly to its target value. Changes to
tween.target
will causetween.current
to move towards it over time, taking account of thedelay
,duration
andeasing
options.<script>import { Tween } from 'svelte/motion';const tween = new Tween(0);</script><input type="range" bind:value={tween.target} /><input type="range" bind:value={tween.current} disabled />5.8.0
constructor
constructor(value: {}, options?: TweenedOptions<T>);
property current
readonly current: {};
property target
target: {};
method of
static of: <U>(fn: () => U, options?: TweenedOptions<U> | undefined) => Tween<U>;
Create a tween whose value is bound to the return value of
fn
. This must be called inside an effect root (for example, during component initialisation).<script>import { Tween } from 'svelte/motion';let { number } = $props();const tween = Tween.of(() => number);</script>
method set
set: (value: T, options?: TweenedOptions<T> | undefined) => Promise<void>;
Sets
tween.target
tovalue
and returns aPromise
that resolves if and whentween.current
catches up to it.If
options
are provided, they will override the tween's defaults.
interface Spring
interface Spring<T> extends Readable<T> {}
property damping
damping: number;
property precision
precision: number;
property stiffness
stiffness: number;
property update
update: (fn: Updater<T>, opts?: SpringUpdateOpts) => Promise<void>;
Deprecated
Only exists on the legacy
spring
store, not theSpring
class
method set
set: { (new_value: T, opts?: SpringUpdateOpts): Promise<void>; (value: T, options?: SpringUpdateOpts): Promise<void>;};
method subscribe
subscribe: (fn: (value: T) => void) => Unsubscriber;
Deprecated
Only exists on the legacy
spring
store, not theSpring
class
namespace svelte/reactivity
module 'svelte/reactivity' {}
function createSubscriber
createSubscriber: ( start: (update: () => void) => (() => void) | void) => () => void;
Returns a
subscribe
function that, if called in an effect (including expressions in the template), calls itsstart
callback with anupdate
function. Wheneverupdate
is called, the effect re-runs.If
start
returns a function, it will be called when the effect is destroyed.If
subscribe
is called in multiple effects,start
will only be called once as long as the effects are active, and the returned teardown function will only be called when all effects are destroyed.It's best understood with an example. Here's an implementation of [
MediaQuery
](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery):import { createSubscriber } from 'svelte/reactivity';import { on } from 'svelte/events';export class MediaQuery {#query;#subscribe;constructor(query) {this.#query = window.matchMedia(`(${query})`);this.#subscribe = createSubscriber((update) => {// when the `change` event occurs, re-run any effects that read `this.current`const off = on(this.#query, 'change', update);// stop listening when all the effects are destroyedreturn () => off();});}get current() {this.#subscribe();// Return the current state of the query, whether or not we're in an effectreturn this.#query.matches;}}5.7.0
class MediaQuery
class MediaQuery extends ReactiveValue<boolean> {}
Creates a media query and provides a
current
property that reflects whether or not it matches.Use it carefully — during server-side rendering, there is no way to know what the correct value should be, potentially causing content to change upon hydration. If you can use the media query in CSS to achieve the same effect, do that.
<script>import { MediaQuery } from 'svelte/reactivity';const large = new MediaQuery('min-width: 800px');</script><h1>{large.current ? 'large screen' : 'small screen'}</h1>{ReactiveValue} 5.7.0
constructor
constructor(query: string, fallback?: boolean);
Parameter query
A media query string
Parameter fallback
Fallback value for the server
class SvelteDate
class SvelteDate extends Date {}
constructor
constructor(...params: any[]);
class SvelteMap
class SvelteMap<K, V> extends Map<K, V> {}
constructor
constructor(value?: Iterable<readonly [K, V]>);
method set
set: (key: K, value: V) => this;
class SvelteSet
class SvelteSet<T> extends Set<T> {}
constructor
constructor(value?: Iterable<T>);
method add
add: (value: T) => this;
class SvelteURL
class SvelteURL extends URL {}
property searchParams
readonly searchParams: SvelteURLSearchParams;
class SvelteURLSearchParams
class SvelteURLSearchParams extends URLSearchParams {}
method [REPLACE]
[REPLACE]: (params: URLSearchParams) => void;
namespace svelte/reactivity/window
module 'svelte/reactivity/window' {}
variable devicePixelRatio
const devicePixelRatio: { readonly current: number };
devicePixelRatio.current
is a reactive view ofwindow.devicePixelRatio
. On the server it isundefined
. Note that behaviour differs between browsers — on Chrome it will respond to the current zoom level, on Firefox and Safari it won't. 5.11.0
variable innerHeight
const innerHeight: ReactiveValue<number>;
innerHeight.current
is a reactive view ofwindow.innerHeight
. On the server it isundefined
. 5.11.0
variable innerWidth
const innerWidth: ReactiveValue<number>;
innerWidth.current
is a reactive view ofwindow.innerWidth
. On the server it isundefined
. 5.11.0
variable online
const online: ReactiveValue<boolean>;
online.current
is a reactive view ofnavigator.onLine
. On the server it isundefined
. 5.11.0
variable outerHeight
const outerHeight: ReactiveValue<number>;
outerHeight.current
is a reactive view ofwindow.outerHeight
. On the server it isundefined
. 5.11.0
variable outerWidth
const outerWidth: ReactiveValue<number>;
outerWidth.current
is a reactive view ofwindow.outerWidth
. On the server it isundefined
. 5.11.0
variable screenLeft
const screenLeft: ReactiveValue<number>;
screenLeft.current
is a reactive view ofwindow.screenLeft
. It is updated inside arequestAnimationFrame
callback. On the server it isundefined
. 5.11.0
variable screenTop
const screenTop: ReactiveValue<number>;
screenTop.current
is a reactive view ofwindow.screenTop
. It is updated inside arequestAnimationFrame
callback. On the server it isundefined
. 5.11.0
variable scrollX
const scrollX: ReactiveValue<number>;
scrollX.current
is a reactive view ofwindow.scrollX
. On the server it isundefined
. 5.11.0
variable scrollY
const scrollY: ReactiveValue<number>;
scrollY.current
is a reactive view ofwindow.scrollY
. On the server it isundefined
. 5.11.0
namespace svelte/server
module 'svelte/server' {}
function render
render: < Comp extends SvelteComponent<any, any, any> | Component<any, {}, string>, Props extends ComponentProps<Comp> = ComponentProps<Comp>>( ...args: {} extends Props ? [ component: Comp extends SvelteComponent<any> ? ComponentType<Comp> : Comp, options?: { props?: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; } ] : [ component: Comp extends SvelteComponent<any> ? ComponentType<Comp> : Comp, options: { props: Omit<Props, '$$slots' | '$$events'>; context?: Map<any, any>; } ]) => RenderOutput;
Only available on the server and when compiling with the
server
option. Takes a component and returns an object withbody
andhead
properties on it, which you can use to populate the HTML when server-rendering your app.
namespace svelte/store
module 'svelte/store' {}
function derived
derived: { <S extends Stores, T>( stores: S, fn: ( values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void ) => Unsubscriber | void, initial_value?: T | undefined ): Readable<T>; <S extends Stores, T>( stores: S, fn: (values: StoresValues<S>) => T, initial_value?: T ): Readable<T>;};
Derived value store by synchronizing one or more readable stores and applying an aggregation function over its input values.
function fromStore
fromStore: { <V>(store: Writable<V>): { current: V }; <V>(store: Readable<V>): { readonly current: V };};
function get
get: <T>(store: Readable<T>) => T;
Get the current value from a store by subscribing and immediately unsubscribing.
function readable
readable: <T>( value?: T | undefined, start?: StartStopNotifier<T> | undefined) => Readable<T>;
Creates a
Readable
store that allows reading by subscription.Parameter value
initial value
function readonly
readonly: <T>(store: Readable<T>) => Readable<T>;
Takes a store and returns a new one derived from the old one that is readable.
Parameter store
store to make readonly
function toStore
toStore: { <V>(get: () => V, set: (v: V) => void): Writable<V>; <V>(get: () => V): Readable<V>;};
function writable
writable: <T>( value?: T | undefined, start?: StartStopNotifier<T> | undefined) => Writable<T>;
Create a
Writable
store that allows both updating and reading by subscription.Parameter value
initial value
interface Readable
interface Readable<T> {}
Readable interface for subscribing.
method subscribe
subscribe: ( this: void, run: Subscriber<T>, invalidate?: () => void) => Unsubscriber;
Subscribe on value changes.
Parameter run
subscription callback
Parameter invalidate
cleanup callback
interface Writable
interface Writable<T> extends Readable<T> {}
Writable interface for both updating and subscribing.
type StartStopNotifier
type StartStopNotifier<T> = ( set: (value: T) => void, update: (fn: Updater<T>) => void) => void | (() => void);
Start and stop notification callbacks. This function is called when the first subscriber subscribes.
Parameter set
Function that sets the value of the store.
Parameter update
Function that sets the value of the store after passing the current value to the update function.
Returns
Optionally, a cleanup function that is called when the last remaining subscriber unsubscribes.
type Subscriber
type Subscriber<T> = (value: T) => void;
Callback to inform of a value updates.
type Unsubscriber
type Unsubscriber = () => void;
Unsubscribes from value updates.
type Updater
type Updater<T> = (value: T) => T;
Callback to update a value.
namespace svelte/transition
module 'svelte/transition' {}
function blur
blur: ( node: Element, { delay, duration, easing, amount, opacity }?: BlurParams | undefined) => TransitionConfig;
Animates a
blur
filter alongside an element's opacity.
function crossfade
crossfade: ({ fallback, ...defaults}: CrossfadeParams & { fallback?: ( node: Element, params: CrossfadeParams, intro: boolean ) => TransitionConfig;}) => [ (node: any, params: CrossfadeParams & { key: any }) => () => TransitionConfig, (node: any, params: CrossfadeParams & { key: any }) => () => TransitionConfig];
The
crossfade
function creates a pair of [transitions](https://svelte.dev/docs/svelte/transition) calledsend
andreceive
. 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, thefallback
transition is used.
function draw
draw: ( node: SVGElement & { getTotalLength(): number }, { delay, speed, duration, easing }?: DrawParams | undefined) => TransitionConfig;
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 agetTotalLength
method, like<path>
and<polyline>
.
function fade
fade: ( node: Element, { delay, duration, easing }?: FadeParams | undefined) => TransitionConfig;
Animates the opacity of an element from 0 to the current opacity for
in
transitions and from the current opacity to 0 forout
transitions.
function fly
fly: ( node: Element, { delay, duration, easing, x, y, opacity }?: FlyParams | undefined) => TransitionConfig;
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.
function scale
scale: ( node: Element, { delay, duration, easing, start, opacity }?: ScaleParams | undefined) => TransitionConfig;
Animates the opacity and scale of an element.
in
transitions animate from the provided values, passed as parameters, to an element's current (default) values.out
transitions animate from an element's default values to the provided values.
function slide
slide: ( node: Element, { delay, duration, easing, axis }?: SlideParams | undefined) => TransitionConfig;
Slides an element in and out.
interface BlurParams
interface BlurParams {}
interface CrossfadeParams
interface CrossfadeParams {}
interface DrawParams
interface DrawParams {}
interface FadeParams
interface FadeParams {}
interface FlyParams
interface FlyParams {}
interface ScaleParams
interface ScaleParams {}
interface SlideParams
interface SlideParams {}
interface TransitionConfig
interface TransitionConfig {}
type EasingFunction
type EasingFunction = (t: number) => number;
namespace svelte/types/compiler/interfaces
module 'svelte/types/compiler/interfaces' {}
type CompileOptions
type CompileOptions = CompileOptions_1;
Deprecated
import this from 'svelte' instead
type Warning
type Warning = Warning_1;
Deprecated
import this from 'svelte' instead
namespace svelte/types/compiler/preprocess
module 'svelte/types/compiler/preprocess' {}
type MarkupPreprocessor
type MarkupPreprocessor = MarkupPreprocessor_1;
Deprecated
import this from 'svelte/preprocess' instead
type Preprocessor
type Preprocessor = Preprocessor_1;
Deprecated
import this from 'svelte/preprocess' instead
type PreprocessorGroup
type PreprocessorGroup = PreprocessorGroup_1;
Deprecated
import this from 'svelte/preprocess' instead
type Processed
type Processed = Processed_1;
Deprecated
import this from 'svelte/preprocess' instead
type SveltePreprocessor
type SveltePreprocessor< PreprocessorType extends keyof PreprocessorGroup_1, Options = any> = SveltePreprocessor_1<PreprocessorType, Options>;
Deprecated
import this from 'svelte/preprocess' instead
Package Files (2)
Dependencies (14)
Dev Dependencies (15)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/svelte
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/svelte)
- HTML<a href="https://www.jsdocs.io/package/svelte"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10763 ms. - Missing or incorrect documentation? Open an issue for this package.