Skip to content

Svelte 5 Exporting $state compile problem #14316

Open
@jdgamble555

Description

@jdgamble555

Describe the bug

If I want to export a shared state, the normal way is to do like this:

Option 1

// rune.svelte.ts

export const rune = <T>(initialValue: T) => {

    let _rune = $state(initialValue);

    return {
        get value() {
            return _rune;
        },
        set value(v: T) {
            _rune = v;
        }
    };
};

Option 2

This also works:

// rune.svelte.ts

export const rune = <T>(initialValue: T) => {
    const _rune = $state({ value: initialValue });
    return _rune;
};

Option 3

However, if I simplify option 2, I get a compile error:

export const rune = <T>(initialValue: T) => $state({ value: initialValue });

// OR

export const rune = <T>(initialValue: T) => {
  return $state({ value: initialValue });
};

I get the error:

$state(...)` can only be used as a variable declaration initializer or a class field

I would expect Option 3 to compile the exact same way as option 2 !?

Reproduction

REPL

Logs

Error message above.

System Info

Svelte 5.2.0

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions