How to import components in Svelte
By Flavio Copes
Learn how to import components in Svelte, where each .svelte file is a single file component you bring in with an import statement and use like an HTML tag.
To import a component in Svelte, you add an import statement inside the script block, pointing at the component’s .svelte file. Then you use it in the markup like an HTML tag.
Svelte provides single file components. Every component is declared into a .svelte file, and in there you can write the HTML markup, the CSS and the JavaScript needed.
Here’s a simple Svelte component example, living in a file called Button.svelte:
<button>A button</button>
You can add CSS and JS to this component, but this plain HTML markup is already the markup of the component. There’s no need to wrap it in another special tag or anything.
For example, here’s the same component with a scoped style:
<button>A button</button>
<style>
button {
background-color: firebrick;
color: white;
}
</style>
That CSS only applies to this component. Another button elsewhere in the app is not affected. This is one of the nicest parts of single file components: styles can’t leak.
Importing the component
To export this markup from this component you don’t have to do anything. You can now import it into any other Svelte component using the import ComponentName from 'componentPath' syntax:
<script>
import Button from './Button.svelte';
</script>
Notice the path includes the .svelte extension. Keep it in the import, it’s how Svelte knows this is a component file.
And now you can use the newly imported component in the markup, like an HTML tag:
<Button />
You can use it as many times as you want. Each <Button /> is an independent instance of the component.
Component names are capitalized
One thing to be careful with: the name you give a component must start with a capital letter.
In the markup, Svelte treats lowercase tags as regular HTML elements. <button /> is the built-in HTML button. <Button /> is your component. If you import a component with a lowercase name, Svelte won’t recognize it in the template, and you’ll stare at a blank spot wondering where your component went.
The name is yours to choose, since it’s a default import. If a file is named Button.svelte but you already use that name, you can rename it on the way in:
<script>
import IconButton from './Button.svelte';
</script>
<IconButton />