Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte - import const from component does not work

I try to import a const value from a Svelte component, but rollup says, the component does not export this value. What do I wrong, or is it a rollup problem ?

related REPL

Component.svelte:

<script>
export const answer = 42;
</script>

App.svelte:

<script>
import { answer } from './Component.svelte';
</script>

<h1>{answer}</h1>

The same problem appears when importing an enum definition.

like image 361
maideas Avatar asked Jul 20 '26 10:07

maideas


2 Answers

Svelte use the export syntax to define a component props. So if you want to use this export like you do in modern javascript modules you have to indicate it to the Svelte compiler using context="module" like:

<script context="module">
    export const answer = 42;
</script>

Checkout the REPL and the doc to learn a little more about it.

like image 151
johannchopin Avatar answered Jul 22 '26 23:07

johannchopin


Try replacing with in Component.svelte. But please note it’ll be read-only no matter how you define it (const or let), so if you want to change the value you may want to create setter or getter function to do that and then access the variable using that.

 <script context="module">
    export const answer = 42;
 </script>
like image 41
A Paul Avatar answered Jul 22 '26 22:07

A Paul