Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
In the preceding exercises, we used runes to add reactivity inside components. But we can also use runes outside components, for example to share some global state.
The <Counter>
components in this exercise are all importing the counter
object from shared.js
. But it’s a normal object, and as such nothing happens when you click the buttons. Wrap the object in $state(...)
:
export const counter = $state({
count: 0
});
This causes an error, because you can’t use runes in normal .js
files, only .svelte.js
files. Let’s fix that — rename the file to shared.svelte.js
.
Then, update the import declaration in Counter.svelte
:
<script>
import { counter } from './shared.svelte.js';
</script>
<script lang="ts">
import { counter } from './shared.svelte.js';
</script>
Now, when you click any button, all three update simultaneously.
You cannot export a
$state
declaration from a module if the declaration is reassigned (rather than just mutated), because the importers would have no way to know about it.
<script>
import Counter from './Counter.svelte';
</script>
<Counter />
<Counter />
<Counter />