javascript / expert
Snippet
Module Context for Shared Singleton Logic
The module context script runs only once when the component definition is loaded, not for every instance. This is perfect for managing shared singletons, caches, or cross-instance counters without a store.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
<script context="module">let instanceCount = 0;export function getGlobalCount() {return instanceCount;}</script><script>instanceCount++;</script><p>Instance number: {instanceCount}</p>
svelte
Breakdown
1
<script context="module">
Defines code that is shared across all instances of this component.
2
let instanceCount = 0;
A private variable scoped to the module, acting as shared state for all component instances.
3
export function getGlobalCount()
An exported function that can be called by other components to access the shared module state.