Svelte 43: Auto-Subscription — The $store Syntax Deep Dive
easy⏱ 5 mincoursesvelte
What $count actually compiles to
Roughly: the compiler inserts let $count; const unsub = count.subscribe(v => $count = v); near the top of the component, plus an onDestroy(unsub). Any assignment like $count++ becomes count.set($count + 1). You get live, auto-updating access with zero manual subscribe/unsubscribe boilerplate.
// Roughly what the compiler generates for `$count`:
let $count;
const unsubscribe = count.subscribe((value) => {
$count = value;
});
onDestroy(unsubscribe);
// And `$count++` becomes:
count.set($count + 1);
$ only exists where the compiler looks: inside .svelte files
A plain .js/.ts module — even one imported by your component — is ordinary JavaScript to every tool in the chain. $count there is just a ReferenceError waiting to happen, because nothing ever compiles that file looking for the $ pattern. To read a store's value from plain JS, import get from 'svelte/store' and call get(count) — a one-time snapshot, not a live subscription.
// mathHelpers.js — a PLAIN module, never compiled by Svelte
import { get } from 'svelte/store';
// WRONG — this is not valid, $count means nothing here:
// export function doubleWrong() { return $count * 2; }
// CORRECT — get() takes a one-off snapshot:
export function doubleCount(store) {
return get(store) * 2;
}
get() snapshots, it doesn't subscribe
get(store) subscribes, captures the current value, and immediately unsubscribes — perfect for one-off reads inside event handlers, useless for keeping UI continuously in sync. For continuously-updated UI, you need $store inside a .svelte file, or a real .subscribe() call kept alive.