javascriptwebimportsveltesveltekit

Svelte export malfunction


I am trying to export constants to svelte but it returns multiple errors this is my main page code


    let username, password
    import {storage} from '../db/client/localStorage'
    import { writable, get} from 'svelte/store'
    import {checkSignIn} from '../db/server/checklogin'
    import Student from './student/Student.svelte'
    import Teacher from './teacher/Teacher.svelte'
    import Admin from './admin/Admin.svelte'
    export let {account} = writable(false)
    if(!storage.get('user') || !storage.get("password")){
    }
    else{ 
       account.set(checkSignIn(storage.get("user"), storage.get("password")))
    }

this is the code that uses an import:

import {account} from '../../components/page.svelte'

I get the error: `app.js:16

   SyntaxError: The requested module '/src/components/page.svelte?t=1678030359672' does not provide an export named 'account' (at checklogin.js?t=1678030359672:4:9)`

I tried putting it into a 'let' but it does not seem to work.


Solution

  • This is not valid:

    export let {account} = writable(false)
    

    If anything it should be

    export let account = writable(false)
    

    But this will export this as property of the component which can only be used with component instances, e.g.

    <Page account={...} />
    

    If you want to import/export a static variable, you have to do so from a <script context="module">. E.g.

    <script context="module">
       export const account = writable(false);
    </script>
    

    Which then would be imported as a named import:

    import { account } from '../../components/page.svelte'
    

    Note, that this rarely makes any sense. There will only be one instance of this variable, regardless of how many instances of the component exist. For a page component, of which there only ever will be one, this might be acceptable.