As well as runes, Svelte 5 introduces a handful of new things you can import, alongside existing ones like getContext
, setContext
and tick
.
sveltepermalink
flushSyncpermalink
Forces any pending effects (including DOM updates) to be applied immediately, rather than in the future. This is mainly useful in a testing context — you'll rarely need it in application code.
<script>
import { flushSync } from 'svelte';
let count = $state(0);
let element;
function onclick() {
flushSync(() => (count += 1));
// without `flushSync`, the DOM would be updated in the future
console.log(element.textContent === String(count));
}
</script>
<span bind:this={element}>{count}</span>
<button {onclick}>update</button>
mountpermalink
Instantiates a component and mounts it to the given target:
ts
import {mount } from 'svelte';importApp from './App.svelte';constapp =mount (App , {target :document .querySelector ('#app'),props : {some : 'property' }});
hydratepermalink
Like mount
, but will reuse up any HTML rendered by Svelte's SSR output (from the render
function) inside the target and make it interactive:
ts
import {hydrate } from 'svelte';importApp from './App.svelte';constapp =hydrate (App , {target :document .querySelector ('#app'),props : {some : 'property' }});
unmountpermalink
Unmounts a component created with mount
or hydrate
:
ts
import {mount ,unmount } from 'svelte';importApp from './App.svelte';constapp =mount (App , {...});// laterunmount (app );
untrackpermalink
To prevent something from being treated as an $effect
/$derived
dependency, use untrack
:
<script>
import { untrack } from 'svelte';
let { a, b } = $props();
$effect(() => {
// this will run when `a` changes,
// but not when `b` changes
console.log(a);
console.log(untrack(() => b));
});
</script>
svelte/reactivitypermalink
Svelte provides reactive Map
, Set
, Date
and URL
classes. These can be imported from svelte/reactivity
and used just like their native counterparts. Demo:
<script>
import { URL } from 'svelte/reactivity';
const url = new URL('https://example.com/path');
</script>
<!-- changes to these... -->
<input bind:value={url.protocol} />
<input bind:value={url.hostname} />
<input bind:value={url.pathname} />
<hr />
<!-- will update `href` and vice versa -->
<input bind:value={url.href} />
svelte/eventspermalink
Svelte provides a way of imperatively attaching DOM event listeners to elements using the attach
export from svelte/events
. This can be used in place of
imperatively doing element.addEventListener
, with that benefit that attach
will allow Svelte to co-ordinate the event through its own event delegation system.
Svelte 5 has its own internal event delegation system that it uses for certain types of events. Rather than creating hundreds or thousands of invidivual event handlers on each element, Svelte creates a single delegated event handler on the root DOM element and manages the bookkeeping itself. This can have a significant impact on performance and memory usage.
ts
import {attach } from 'svelte/events';attach (element , 'click', () => {console .log ('element was clicked');});
Additionally, attach
returns a function that easily allows for removal of the attached event handler:
ts
import {attach } from 'svelte/events';constremove =attach (element , 'click', () => {console .log ('element was clicked');});// ...remove ();
Note:
attach
also accepts 4th optional argument for defining the options for the event handler. This matches that of the options argument (EventListenerOptions
) foraddEventListener
.
svelte/serverpermalink
renderpermalink
Only available on the server and when compiling with the server
option. Takes a component and returns an object with html
and head
properties on it, which you can use to populate the HTML when server-rendering your app:
ts
import {render } from 'svelte/server';importApp from './App.svelte';constresult =render (App , {props : {some : 'property' }});
svelte/elementspermalink
Svelte provides built-in DOM types. A common use case for DOM types is forwarding props to an HTML element. To properly type your props and get full intellisense, your props interface should extend the attributes type for your HTML element:
<script lang="ts">
import { HTMLAttributes } from 'svelte/elements';
interface Props extends HTMLAttributes<HTMLDivElement> {
username: string;
}
let { username, ...rest }: Props = $props();
</script>
<div {...rest}>
Hi, {username}!
</div>
You can use
ComponentProps<ImportedComponent>
, if you wish to forward props to a Svelte component.
Svelte provides a best-effort of all the HTML DOM types that exist. If an attribute is missing from our type definitions, you are welcome to open an issue and/or a PR fixing it. For experimental attributes, you can augment the existing types locally by creating a .d.ts
file:
ts
import {HTMLButtonAttributes } from 'svelte/elements';declare module 'svelte/elements' {export interfaceSvelteHTMLElements {'custom-button':HTMLButtonAttributes ;}// allows for more granular control over what element to add the typings toexport interfaceHTMLButtonAttributes {veryexperimentalattribute ?: string;}}export {}; // ensure this is not an ambient module, else types will be overridden instead of augmented
The .d.ts
file must be included in your tsconfig.json
file. If you are using the standard "include": ["src/**/*"]
, this just means the file should be placed in the src
directory.