How to Import Component in Svelte: Simple Syntax and Example
In Svelte, you import a component using the ES module
import statement inside the <script> tag. For example, import MyComponent from './MyComponent.svelte'; lets you use <MyComponent /> in your template.Syntax
To import a component in Svelte, use the import keyword inside the <script> tag. The syntax is:
import ComponentName from './ComponentFile.svelte';- imports the component from a file.ComponentNameis the name you use in your template.'./ComponentFile.svelte'is the relative path to the component file.
svelte
<script> import ComponentName from './ComponentFile.svelte'; </script>
Example
This example shows how to import and use a child component called Greeting.svelte inside a parent component.
svelte
<!-- Greeting.svelte --> <script> export let name = 'Friend'; </script> <p>Hello, {name}!</p> <!-- App.svelte --> <script> import Greeting from './Greeting.svelte'; </script> <main> <Greeting name="Alice" /> <Greeting name="Bob" /> </main>
Output
<p>Hello, Alice!</p>
<p>Hello, Bob!</p>
Common Pitfalls
Common mistakes when importing components in Svelte include:
- Forgetting to include the
.svelteextension in the import path. - Using incorrect relative paths, causing module not found errors.
- Trying to import components outside the
<script>tag. - Not capitalizing component names, which is a convention to distinguish components from HTML tags.
svelte
<!-- Wrong: missing .svelte extension --> <script> import Greeting from './Greeting'; // ❌ This will cause an error </script> <!-- Right: include .svelte extension --> <script> import Greeting from './Greeting.svelte'; // ✅ Correct </script>
Quick Reference
Remember these tips when importing components in Svelte:
- Always import inside the
<script>tag. - Use the
importkeyword with the component file path including.svelte. - Use PascalCase for component names.
- Use the imported component as a tag in your markup.
Key Takeaways
Import Svelte components using
import ComponentName from './ComponentName.svelte'; inside the <script> tag.Always include the
.svelte file extension in the import path.Use the imported component as a custom tag in your template, e.g.,
<ComponentName />.Keep component names capitalized to distinguish them from HTML elements.
Check relative paths carefully to avoid module not found errors.