# Svelte Custom Element on Astro There is a demo shows you the minimal code and working example of how to set up a astro project to make use of [Svelte compiles to Custom Element feature](https://svelte.dev/docs/svelte/custom-elements) at https://stackblitz.com/edit/svelte-ce-on-astro-demo?file=README.md. ## And here is the gist - Svelte allow you to compile its component to a custom element (aka Web Component) - https://svelte.dev/docs/svelte/custom-elements - Astro doesn't have a guide on how to do this but I figured out how to and thus the sharing - https://stackblitz.com/edit/svelte-ce-on-astro-demo?file=README.md ## Tour of the main code ### The component ```svelte
{ message }:
``` ### Good old Astro client island from a Svelte component ```astro --- // pages/regular.astro import Layout from '../layouts/Layout.astro'; import SvelteCounter from '../components/SvelteCounter.svelte'; ---
``` ### Mixed usage that lets you think it just works ```astro --- // pages/mixed.astro import Layout from '../layouts/Layout.astro'; import SvelteCounter from '../components/SvelteCounter.svelte'; ---
``` ### Standalone usage reveals the extra import required ```astro --- // pages/as-web-comp.astro import Layout from '../layouts/Layout.astro'; ---
initializing...
``` _`` above is not important but to demonstrate what I learned from https://blog.jim-nielsen.com/2023/html-web-components/._ #### But why client side `` will basically do a similar thing without hydrating since there is none to hydrate but to register a CE. Also this code runs as `type="module"` by default as that's how Astro works which means it's automatically `defer`ed. ### with AlpineJS This usage is why I was interested in utilizing Svelte's custom element compiling in the first place. ```astro --- // pages/with-alpine.astro import Layout from '../layouts/Layout.astro'; ---
``` ### Svelte config (via astro.config.mjs) ```mjs // astro.config.mjs // @ts-check import { defineConfig } from 'astro/config'; import svelte from '@astrojs/svelte'; // https://astro.build/config export default defineConfig({ integrations: [ svelte({ compilerOptions: { customElement: true, // this is the one that what should tell Svelte to compile components to CEs }, }), ], // this section is not necessary but could be helpful to see authored source code with the production build (it's already available at development build though) vite: { build: { sourcemap: true, }, }, }); ``` There are a bit more code you can take a look and also get to interact with the demo at https://stackblitz.com/edit/svelte-ce-on-astro-demo?file=README.md.