Sasha
Sasha

Reputation: 8705

Svelte 5 - Uncaught ReferenceError: $state is not defined

I am trying to make Svelte 5 project (I know it is still in alpha, but I want to play a bit with it), and I am using this as a template for now

My App.svelte

<script>
    import { withPrevSignals } from './withPrev'

    const color = withPrevSignals('green')

    let inputVal = $state('')

    function save() {
        color.curr = inputVal;
        inputVal = ''
    }
</script>

<p>Prev: {color.prev}</p>
<p>Curr: {color.curr}</p>
<input bind:value={inputVal} />
<button on:click={save}>Save</button>
<button on:click={color.undo}>Undo</button>

withPrev.js

export function withPrevSignals(initialValue) {
    let curr = $state(initialValue)
    let prev = $state(undefined)

    function undo() {
        curr = prev
        prev = undefined
    }
    return {
        get curr() { return curr },
        set curr(newValue) {
            prev = curr
            curr = newValue
        },
        get prev() { return prev },
        undo
    }
}

I keep getting an Uncaught ReferenceError: $state is not defined both in the svelte 5 playground and on the local. What am I doing wrong here?

Upvotes: 4

Views: 3675

Answers (2)

yonran
yonran

Reputation: 19164

For people like me who have googled this error “ReferenceError: $state is not defined”, one cause of this error is that the source code upgraded to svelte 5 but you still have an old svelte 4 installed locally. If this is the case, make sure to install the proper svelte 5 that package.json requires:

  • If you are running npm directly, then run npm ci again (or whichever package manager the code uses e.g. yarn install --immutable).
  • Else if you are running docker-compose that contains a build: block whose Dockerfile runs npm ci or equivalent, then run docker-compose up --build to rebuild the image that installs npm dependencies.

Upvotes: 1

brunnerh
brunnerh

Reputation: 185180

Files using runes require the extension .svelte.js or .svelte.ts (docs).

(For tests, which commonly end in .spec.js/.test.js or the like, the check was changed to allow .svelte in other places as well, so you can have a thing.svelte.spec.js.)

Fixed Playground

Upvotes: 4

Related Questions