Astro JS - Svelte Integration



What is Svelte?

Svelte is an open-source Javascript framework designed to build user interfaces, mainly for web applications. It is a popular tool for creating user interface parts, like a navigation bar, comment section, or contact form, that people see and use in their web browsers. The Svelte compiler turns your components into JavaScript, which helps display the HTML for the page, and into CSS, which styles the page.

Svelte Integration in Astro

Astro provides built-in support for Svelte by using Svelte adapter to render Svelte components. You can write your favorite UI components in Svelte and optimize them for performance using Astro. Let's see how to integrate Svelte with Astro.

Get Started With Svelte in Astro

Follow the steps below to integrate Svelte with Astro:

Step 1: Install Svelte Adapter

First, you need to install the Svelte adapter for Astro. You can do this using the following command:

>> npm install @astrojs/svelte

Step 2: Configure Svelte in Astro

Next step is to apply the integration to your astro.config.ts and tsconfig.json files using the integrations property:

import { defineConfig } from 'astro/config';
import svelte from '@astrojs/svelte';

export default defineConfig({
  // ...
  integrations: [svelte()],
});

Now, Add following code to your typescript configuration file (tsconfig.json)

{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"],
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react"
  }
}

Step 3: Create a Svelte Component

Now, you can create a Svelte component in your Astro project. You can keep your components in the '/src/components' directory. Here is an example of a simple Svelte component:

// src/components/Counter.svelte

<script>
  let count = 0;
  function increment() {
    count += 1;
  } 
</script>

Step 4: Use the Svelte Component in Astro Page

Now, you can use the Svelte component in your Astro page. You can import the component and use it in your Astro page like this:

// src/pages/index.astro

<script context="module">
  import Counter from '../components/Counter.svelte';
</script>

<Counter/>

<style>
  /* Add your styles here */
</style>

That's it! You have successfully integrated Svelte with Astro. You can now create and use Svelte components in your Astro project.

Set Svelte Options in Astro

The svelte options are used to customize svelte compiler. You can set options either by passing them to the svelte integration in astro.config.mjs or in svelte.config.js. The options in astro.config.mjs will take precedence over the options in svelte.config.js if both are present:

// File - /astro.config.mjs

import { defineConfig } from 'astro/config';
import svelte from '@astrojs/svelte';

export default defineConfig({
    integrations: [svelte({ extensions: ['.svelte'] })],
});
Advertisements