Skip to content

How to export functions and variables from a Svelte component

Learn how to export functions and variables from a Svelte component

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

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

What if you want to export something more than the default export?

Well, you must export it from a special script tag into the component, with the context="module" attribute.

Here’s an example. Say you have a Button component in Button.svelte:

<button>A button</button>

and you want to provide other components the ability to change the color of the button. You could use props, that’s one example. Or you can provide a function, called changeColor.

You write and export it in this special 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 component.

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

<script>
import Button, { changeColor } from './Button.svelte'
</script>
→ Download my free Svelte Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about svelte: