Export functions and variables from a Svelte component

By

Learn how to export functions and variables from a Svelte component using a script tag with context='module', so other components can import them.

~~~

You can export functions and variables from a Svelte component by declaring them in a <script> tag with the context="module" attribute. Anything you export from there becomes a named export of the component file, and other components can import it.

You know that you can import a Svelte component into another using this syntax:

<script>
import Button from './Button.svelte'
</script>

Button is the default export. Every Svelte file exports its component this way, automatically. But what if you want to export something more than the default export?

Why do we need a special script tag?

A Svelte component can have two kinds of script tags.

The normal <script> tag runs once for every instance of the component. Render 10 buttons, and it runs 10 times.

The <script context="module"> tag runs once, when the module is first evaluated. It does not belong to any single instance.

That’s where your exports must live. You can’t export values from the normal script tag. There, export let has a special meaning: it declares a prop.

An example

Say you have a Button component in Button.svelte:

<button>A button</button>

and you want to provide other components a changeColor function.

You write and export it in the module-level script tag:

<script context="module">
export function changeColor() {
  //...add logic..
}
</script>

<button>A button</button>

Warning: I did not implement the actual functionality, but you get the idea.

Note that you can have another “normal” script tag in the same component. The two coexist just fine.

Now other components can import Button, which is the default export, and the changeColor function too:

<script>
import Button, { changeColor } from './Button.svelte'
</script>

Be careful with instance state

The module script has no access to the variables defined in the normal script tag. Those belong to each instance, and the module script runs before any instance exists.

So changeColor() cannot reach into a specific button on the page and update its state. If you try, you’ll get a reference error, because those variables don’t exist in the module scope.

If you need to control a single component instance, use props instead.

Exported module functions work best for logic that’s independent from any instance: shared helpers, constants, or state shared across all copies of the component.

Tagged: Svelte · All topics
~~~

Related posts about svelte: