0
0
Astroframework~5 mins

Svelte components in Astro

Choose your learning style9 modes available
Introduction

Svelte components let you build interactive parts easily. Astro helps you use Svelte components inside your website smoothly.

You want to add a button that changes when clicked without reloading the page.
You need a form that updates live as users type.
You want to use Svelte's simple syntax inside an Astro project.
You want to mix static content with dynamic Svelte parts.
You want faster websites by loading only needed JavaScript.
Syntax
Astro
---
import MyComponent from '../components/MyComponent.svelte';
---

<MyComponent someProp="value" />
Use the frontmatter section (---) to import your Svelte component.
Use the component as a tag in your Astro file to include it.
Examples
This example imports a simple Counter Svelte component and uses it in Astro.
Astro
---
import Counter from '../components/Counter.svelte';
---

<Counter />
Here, a Greeting component receives a prop called name to show a personalized message.
Astro
---
import Greeting from '../components/Greeting.svelte';
---

<Greeting name="Alice" />
Sample Program

This Astro page imports a Svelte component called ClickMe and shows it inside the page. The ClickMe component can have interactive behavior like a button that changes text when clicked.

Astro
---
import ClickMe from '../components/ClickMe.svelte';
---

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Svelte in Astro Example</title>
  </head>
  <body>
    <h1>Welcome to Astro with Svelte!</h1>
    <ClickMe />
  </body>
</html>
OutputSuccess
Important Notes

Make sure you have installed the @astrojs/svelte integration to use Svelte components.

Svelte components in Astro only load their JavaScript when needed, helping your site stay fast.

You can pass props to Svelte components just like HTML attributes.

Summary

Svelte components add interactivity inside Astro projects.

Import Svelte components in the frontmatter and use them as tags.

This helps build fast, interactive websites easily.