Skip to content

Commit 8a2c97a

Browse files
authored
fix: extend derived/state validation error to indirect exports (#14039)
Closes #14029
1 parent 1434f48 commit 8a2c97a

File tree

6 files changed

+61
-0
lines changed

6 files changed

+61
-0
lines changed

.changeset/perfect-queens-reflect.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: extend derived/state validation error to indirect exports

packages/svelte/src/compiler/phases/2-analyze/visitors/ExportNamedDeclaration.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,21 @@ export function ExportNamedDeclaration(node, context) {
5757
}
5858
}
5959
}
60+
61+
if (!context.state.ast_type /* .svelte.js module */ || context.state.ast_type === 'module') {
62+
for (const specified of node.specifiers) {
63+
const binding = context.state.scope.get(specified.local.name);
64+
65+
if (!binding) continue;
66+
67+
if (binding.kind === 'derived') {
68+
e.derived_invalid_export(node);
69+
}
70+
71+
if ((binding.kind === 'state' || binding.kind === 'raw_state') && binding.reassigned) {
72+
e.state_invalid_export(node);
73+
}
74+
}
75+
}
6076
}
6177
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
error: {
5+
code: 'derived_invalid_export',
6+
message:
7+
'Cannot export derived state from a module. To expose the current derived value, export a function returning its value',
8+
position: [70, 76]
9+
}
10+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
let count = $state(0);
2+
3+
const double = $derived(count * 2);
4+
5+
export { double };
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { test } from '../../test';
2+
3+
export default test({
4+
error: {
5+
code: 'state_invalid_export',
6+
message:
7+
"Cannot export state from a module if it is reassigned. Either export a function returning the state value or only mutate the state value's properties",
8+
position: [211, 220]
9+
}
10+
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const object = $state({
2+
ok: true
3+
});
4+
5+
let primitive = $state('nope');
6+
7+
export function update_object() {
8+
object.ok = !object.ok;
9+
}
10+
11+
export function update_primitive() {
12+
primitive = 'yep';
13+
}
14+
15+
export { object, primitive };

0 commit comments

Comments
 (0)