Docs

Shared state

Move reactive state out of components into .svelte.ts modules to share it anywhere.

Reactive modules

Runes work in .svelte.ts files too. Export state and functions that mutate it.

cart.svelte.ts
ts
export const cart = $state({ items: [] as string[] });

export function add(item: string) {
  cart.items.push(item);
}

Using it

svelte
svelte
<script>
  import { cart, add } from './cart.svelte.ts';
</script>

<button onclick={() => add('apple')}>Add</button>
<p>{cart.items.length} items</p>