You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation/docs/01-introduction/04-svelte-js-files.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: .svelte.js and .svelte.ts files
4
4
5
5
Besides `.svelte` files, Svelte also operates on `.svelte.js` and `.svelte.ts` files.
6
6
7
-
These behave like any other `.js` or `.ts` module, except that you can use runes. This is useful for creating reusable reactive logic, or sharing reactive state across your app.
7
+
These behave like any other `.js` or `.ts` module, except that you can use runes. This is useful for creating reusable reactive logic, or sharing reactive state across your app (though note that you [cannot export reassigned state]($state#Passing-state-across-modules)).
8
8
9
9
> [!LEGACY]
10
10
> This is a concept that didn't exist prior to Svelte 5
...though if you find yourself writing code like that, consider using [classes](#Classes) instead.
253
+
254
+
## Passing state across modules
255
+
256
+
You can declare state in `.svelte.js` and `.svelte.ts` files, but you can only _export_ that state if it's not directly reassigned. In other words you can't do this:
257
+
258
+
```js
259
+
/// file: state.svelte.js
260
+
exportlet count =$state(0);
261
+
262
+
exportfunctionincrement() {
263
+
count +=1;
264
+
}
265
+
```
266
+
267
+
That's because every reference to `count` is transformed by the Svelte compiler — the code above is roughly equivalent to this:
268
+
269
+
```js
270
+
/// file: state.svelte.js (compiler output)
271
+
// @filename: index.ts
272
+
interface Signal<T> {
273
+
value:T;
274
+
}
275
+
276
+
interface Svelte {
277
+
state<T>(value?:T): Signal<T>;
278
+
get<T>(source: Signal<T>):T;
279
+
set<T>(source: Signal<T>, value:T):void;
280
+
}
281
+
declare const $:Svelte;
282
+
// ---cut---
283
+
exportlet count =$.state(0);
284
+
285
+
exportfunctionincrement() {
286
+
$.set(count, $.get(count) +1);
287
+
}
288
+
```
289
+
290
+
> [!NOTE] You can see the code Svelte generates by clicking the 'JS Output' tab in the [playground](/playground).
291
+
292
+
Since the compiler only operates on one file at a time, if another file imports `count` Svelte doesn't know that it needs to wrap each reference in `$.get` and `$.set`:
293
+
294
+
```js
295
+
// @filename: state.svelte.js
296
+
exportlet count =0;
297
+
298
+
// @filename: index.js
299
+
// ---cut---
300
+
import { count } from'./state.svelte.js';
301
+
302
+
console.log(typeof count); // 'object', not 'number'
303
+
```
304
+
305
+
This leaves you with two options for sharing state between modules — either don't reassign it...
0 commit comments