2
votes

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.

2
try replacing <script> with <script context="module"> in Component.svelte. I have added this as a answer below. - A Paul
more about it in here: svelte.dev/tutorial/module-exports - kibe

2 Answers

3
votes

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.

1
votes

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>