Welcome

Technology

Export Svelte as a component

Export Svelte as a component

Find out how to export your Svelte app as a component.

Integrating a Svelte Component into an Astro.js Project

Set Up a Svelte Project

  1. Initialize a new Svelte project:
    npx degit sveltejs/template svelte-app
    cd svelte-app
    npm install
    

Create Your Svelte Component

  1. In src, create your Svelte component, e.g., MyComponent.svelte:
    <script>
      export let name;
    </script>
    
    <style>
      /* Add your styles here */
    </style>
    
    <div>
      Hello {name}!
    </div>
    

Build the Svelte Component

  1. Install Vite and create a build configuration:
    npm install vite @sveltejs/vite-plugin-svelte --save-dev
    
  2. Create a vite.config.js file in the root of your project:
    import { defineConfig } from 'vite';
    import { svelte } from '@sveltejs/vite-plugin-svelte';
    
    export default defineConfig({
      plugins: [svelte()],
      build: {
        lib: {
          entry: 'src/MyComponent.svelte',
          name: 'MyComponent',
          fileName: (format) => `my-component.${format}.js`
        },
        rollupOptions: {
          external: ['svelte/internal'],
          output: {
            globals: {
              'svelte/internal': 'svelte'
            }
          }
        }
      }
    });
    

Build the Library

  1. Run the build command:
    npx vite build
    

Include in Astro Project

  1. Copy the built file (dist/my-component.umd.js) to your Astro project.

  2. In your Astro project, install the Svelte integration:

    npm install @astrojs/svelte
    
  3. Update astro.config.mjs to include the Svelte integration:

    import { defineConfig } from 'astro/config';
    import svelte from '@astrojs/svelte';
    
    export default defineConfig({
      integrations: [svelte()],
    });
    

Use the Svelte Component in Astro

  1. In an Astro component, import and use the Svelte component:
    ---
    import { SvelteComponent } from 'svelte';
    import MyComponent from './path/to/my-component.umd.js';
    ---
    
    <MyComponent name="Astro"/>
    
Available in

MENU

PROJECT Management

Articles & Blogs

LEGAL