Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Improve documentation regarding .svelte.js and svelte.ts $state export rules #15586

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions documentation/docs/01-introduction/04-svelte-js-files.md
Original file line number Diff line number Diff line change
@@ -8,3 +8,25 @@ These behave like any other `.js` or `.ts` module, except that you can use runes

> [!LEGACY]
> This is a concept that didn't exist prior to Svelte 5

### Sharing `$state` Across Modules

When exporting reactive state from a module using `$state`, ensure it remains reactive and predictable by following one of these approaches:

- **Export a function**: Return the `$state` value from a function to encapsulate and provide access to it.
- **Export an object**: Use `$state` with an object and mutate its properties to trigger reactivity.

Reassigning an exported `$state` variable (e.g., `count = 5`) in the module where it’s defined is not allowed, as it breaks reactivity tracking. Instead, choose one of these patterns:

```javascript
// Option 1: Export a function
export function getCount() {
return $state(0);
}

// Option 2: Export an object and mutate properties
export let state = $state({ count: 0 });
// Later: state.count += 1; (valid mutation)
```

> [!NOTE] You cannot reassign an exported $state variable (e.g., count = 5) in its module. Either export a function returning the state or use an object and mutate its properties to maintain reactivity. See [Compiler Errors: state_invalid_export](https://svelte.dev/docs/svelte/compiler-errors#state_invalid_export) for Svelte-specific details, and [MDN: JavaScript export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) for how JavaScript module bindings work.