Svelte State 02 🧡 Universal .svelte.ts Rune Modules — Writing reactive state outside components and the primitive trap
The true power of Svelte 5 reactivity lies in its ability to escape the boundaries of component files. By utilizing .svelte.ts (or .svelte.js) files, you can create “Rune Modules”—standalone pieces of logic that maintain reactive state independent of any specific component lifecycle. This allows for clean, injectable state management that works consistently across your entire application.
However, moving state into external modules introduces a common trap: if you export a raw primitive declared with $state(), you often lose the reactive proxy upon import, leading to “stale” values that fail to trigger UI updates. This chapter explains the .svelte.ts convention, why primitive exports fail to update, and how to properly encapsulate your state within objects or classes to ensure full reactivity.
Key point: Reactive state must be encapsulated within an object or class when exported from a module, because exporting a raw $state() primitive often loses the reactive proxy binding; using objects ensures that components always reference the underlying reactive state reference rather than a detached value.
Why exists
- The Component-Coupling problem. Moving state to
.svelte.tsremoves the need for prop-drilling and ensures your business logic isn’t trapped inside the UI-rendering lifecycle. - The Primitive Export trap. Directly exporting
export let count = $state(0)causes the value to be treated as a static import in many environments, breaking the reactivity chain because the variable reference isn’t tracked across module boundaries. - The Global Store requirement. Applications require a way to share data (like user auth or themes) across disjointed UI trees, and
.svelte.tsmodules serve as the modern, lightweight replacement for the oldwritablestore pattern. - The Testability problem. By isolating state logic into modules, you can unit test your data mutation logic without mounting or rendering a single component.
- The Encapsulation problem. Grouping related state and mutation functions in a single module creates a cleaner API that is easier to document and maintain than scattered
letdeclarations.
a. The .svelte.ts convention
The .svelte.ts extension is a special signal to the Svelte compiler. It tells Svelte that this file is allowed to use runes like $state() and $derived(). Files without this extension will cause errors if you attempt to use runes inside them. This convention allows you to write standard TypeScript that is reactive by default.
// theme.svelte.ts
export const theme = $state({
mode: 'dark',
toggle() {
this.mode = this.mode === 'dark' ? 'light' : 'dark';
}
});
By exporting an object, you ensure that any component importing this module will be referencing the same object instance. Because the object is defined with $state, the properties inside are reactive, and Svelte’s proxy will correctly track any mutations made to those properties.
b. Why raw primitive exports fail
When you write export let count = $state(0), Svelte compiles this into a variable. When another file imports this count, it receives the value of the state at the time of access or a reference to a variable that isn’t properly proxied for cross-module reactivity. This is why you must avoid exporting primitives directly.
// ❌ THIS WILL FAIL TO SYNC
export let counter = $state(0);
// ✅ THIS WORKS
export const state = {
get counter() { return this._counter; },
set counter(v) { this._counter = v; },
_counter: $state(0)
};
When you export an object, you are exporting a reference to a container. When a component reads from that container, it is reading from a reactive proxy. When it modifies a property on that object, the proxy is notified. This is the “Gold Standard” for cross-module state management.
c. Encapsulating with Classes
Classes are an excellent way to organize state in .svelte.ts files. They allow you to bundle state, derived values, and mutation methods together into a clean, reusable interface. When you instantiate a class and export the instance, you provide a stable, reactive reference to your app.
// counter.svelte.ts
class Counter {
count = $state(0);
increment() { this.count += 1; }
get double() { return this.count * 2; }
}
export const counter = new Counter();
Components simply import counter and call counter.increment(). Because the instance is created at the module level, every component that imports this file shares the exact same Counter instance, making it effectively a global, reactive store that requires zero boilerplate.
Complete Example Session
// ============================================
// PART 1: THE COUNTER MODULE
// ============================================
// counter.svelte.ts
class Counter {
val = $state(0);
inc() { this.val++; }
}
export const counter = new Counter();
// ============================================
// PART 2: CONSUMPTION IN COMPONENT
// ============================================
// CounterComponent.svelte
import { counter } from './counter.svelte.ts';
// ============================================
// PART 3: REACTIVITY CHECK
// ============================================
// Clicking this updates the global state
<button onclick={() => counter.inc()}>
Count: {counter.val}
</button>
// ============================================
// PART 4: DERIVED IN MODULE
// ============================================
// counter.svelte.ts (added)
get double() { return this.val * 2; }
The session shows how to wrap state in a class inside a .svelte.ts file, export an instance, and use it in multiple components while maintaining full reactivity.
Quick Reference
The Reactive Export Rules
| Pattern | Reactive? | Why? |
|---|---|---|
export let x = $state(0) | ❌ | Primitive reference loss |
export const x = { val: $state(0) } | ✅ | Proxy maintained on object |
export const x = new Class() | ✅ | Stable instance reference |
File Conventions
| Extension | Purpose |
|---|---|
.svelte.ts | Allows runes in non-component files |
.ts | Standard TS (No runes allowed) |
Best Practices
✅ Do This:
// Encapsulate in an object
export const store = { count: $state(0) }; // ✅
// Use a class for complex state
export const user = new UserStore(); // ✅
// Export a single instance of the store
export const instance = new Store(); // ✅
❌ Don’t Do This:
// Don't export raw state variables
export let count = $state(0); // ❌
// Don't mix state and logic in the component
// (move logic to the .svelte.ts module) // ❌
// Don't forget the .svelte extension
// (using .ts for runes results in a compiler error) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No reactivity | Importing direct primitive | Use object container |
| Build errors | Using runes in .ts file | Rename to .svelte.ts |
| Multiple instances | Re-instantiating inside components | Export instance from module |
Real-World Examples
1. Theme Store
const theme = { mode: $state('dark') };
export { theme };
2. Auth Store
class Auth { user = $state(null); login(u) { ... } }
export const auth = new Auth();
3. Data Pagination
class Pager { page = $state(1); next() { this.page++ } }
4. Form Helper
class Form { errors = $state({}); validate() { ... } }
5. Toast Notifications
class Toaster { messages = $state([]); add(m) { ... } }
6. User Settings
export const settings = { lang: $state('en') };
7. Global Timer
class Timer { time = $state(0); start() { ... } }
8. Cart Logic
class Cart { items = $state([]); total = $derived(...) }
9. Keyboard Shortcuts
class Keys { pressed = $state(''); }
10. API Data Caching
class Cache { data = $state(null); fetch() { ... } }
Visual
The Reactive Proxy Chain
┌──────────────────────────────────────────────┐
│ .svelte.ts Module │
│ ┌────────────────────────┐ │
│ │ export const obj = { │ │
│ │ count: $state(0) │ │
│ │ } │ │
│ └──────────┬─────────────┘ │
│ │ (Proxy reference) │
│ COMPONENT ▼ │
│ obj.count ◄─── Reactive binding │
└──────────────────────────────────────────────┘
Primitive Export Trap
┌──────────────────────────────────────────────┐
│ .svelte.ts Module │
│ export let x = $state(0); │
│ │ │
│ COMPONENT │ │
│ import {x} ┘ │
│ x = 10; <─── Only changes local reference. │
│ UI DOES NOT UPDATE! │
└──────────────────────────────────────────────┘
Class-based Encapsulation
┌──────────────────────────────────────────────┐
│ class Store { │
│ data = $state(0); │
│ } │
│ export const store = new Store(); │
│ │
│ Importing `store` gives you the instance. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| File Extension | .svelte.ts |
| Best Pattern | Object or Class encapsulation |
| Common Trap | Exporting raw $state primitives |
| Reactivity Scope | Cross-module reference |
Key takeaways:
- Use
.svelte.tsfor logic. Any file containing runes must have the.svelteprefix to be processed by the Svelte compiler. - Avoid raw exports. Never export a
$state()directly; always place it inside an object or a class instance to maintain the reactive proxy. - Classes are powerful. They allow you to bundle state and logic, providing an easy-to-use API for your components.
- Singletons are standard. Exporting a single instance of a class from your
.svelte.tsfile acts as a globally shared, reactive singleton. - Reactivity is reference-based. Components update because they track the reference to the object property; by exporting an object, you ensure that reference remains stable and tracked across files.
Remember: Moving state to .svelte.ts modules is the bridge from “component-scoped data” to “application-wide state.” By following the object/class encapsulation pattern, you avoid the common trap of primitive reactivity loss and unlock a clean, modular way to manage your app’s data flow.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!