Skip to content

Svelte 5 context module export class with state rune error #10034

@gert-wijns

Description

@gert-wijns

Describe the bug

Exporting a class with a state rune from a .svelte file using a context="module" script causes compilation errors in some cases.

image

Reproduction

Error: $state() can only be used as a variable declaration initializer or a class field (svelte)
export class Foo {
value = $state()
}

Additional info:
These are the steps I took:
I created a new project using
npm create svelte@latest my-app
Skeleton project
Typescript syntax
Svelte 5 preview

Then I updated the svelte version in package.json to ^5.0.0-next.27 (it's initially just 1)

Then I open the project in vscode, npm install and check.
npm run check -> no errors

Then I added this to +page.svelte:

<script lang="ts" context="module"> export class Foo { value = $state("I'm a value ") } </script>

npm run check -> no errors

Then I added a second file next to it, Test.svelte, containing the same code
npm run check -> I get the error about $state
c:\Personal\workspaces\Test\my-app\src\routes\Test.svelte:3:17
Error: $state() can only be used as a variable declaration initializer or a class field (svelte)
export class Foo {
value = $state("I'm a value ")
}

Then I went back and removed the content of the script tag in +page.ts (but left the empty script tag)
npm run check -> Still an error about $state

Then I removed the script tag from +page.svelte entirely (leaving only the script tag in Test.svelte with the class and rune)
npm run check -> no errors

Logs

No response

System Info

System:
    OS: Windows 11 10.0.22621
    CPU: (12) x64 Intel(R) Core(TM) i7-10850H CPU @ 2.70GHz
    Memory: 5.20 GB / 31.72 GB
  Binaries:
    Node: 20.8.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - C:\Program Files\nodejs\yarn.CMD
    npm: 10.1.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22621.1265.0), Chromium (120.0.2210.61)
    Internet Explorer: 11.0.22621.1
  npmPackages:
    svelte: ^5.0.0-next.27 => 5.0.0-next.27

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions