sveltesvelte-5

How to use a global $derived in Svelte 5?


I'm trying to create a global state with Svelte 5 and runes:

// store.svelte.ts
export const person = ({
    name: '',
});

export const mrName = $derived('Mr. ' + person.name); // <-- problem!

I can't make $derived to work:

Cannot export derived state from a module.

6 |  export const mrName = $derived("Mr. " + person.name);
                                                           ^
7 |

What's the correct approach to a global $derived?


Solution

  • Derived state in svelte.ts/svelte.ts files needs to be wrapped in a class or a function.

    Class

    You can use a constructor to set initial state, but that wasn't in your example, so I didn't include it here.

    Classes add getters/setters for each property when it is compiled.

    // store.svelte.ts
    export class Person {
      name = $state('')
      mrName = $derived("Mr. " + this.name)
    }
    

    Reference: https://svelte.dev/docs/svelte/$state#Classes

    Function

    Need to use get() to return the current state values from the function, otherwise it will only show the values at the time the function was initially called.

    // store.svelte.ts
    export const Person = () => {
      let name = $state('')
      let mrName = $derived("Mr. " + name)
      return {
        get name() { return name },
        get mrName() { return mrName }
      }
    }
    

    There was a reference for the get() requirement in the svelte 5 preview docs but haven't found it yet in the new docs.