Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
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 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More svelte tutorials:
- Getting started with Svelte - a short tutorial
- How to work with props in Svelte
- How to import components in Svelte
- How to export functions and variables from a Svelte component
- Svelte templates: conditional logic
- How to rerender a Svelte component on demand
- Svelte Slots
- How to add comments in Svelte templates
- Svelte Bindings
- Handling State Updates in Svelte
- Reactive Statements in Svelte
- Svelte Lifecycle Events
- Svelte templates: loops
- Resolve promises in Svelte templates
- Working with events in Svelte
- Cross-component State Management in Svelte
- How to access a URL parameter in Sapper outside of script module
- How to dynamically apply CSS in Svelte
- How to redirect to a URL in Sapper
- How to simulate a for loop in Svelte templates