Table of Contents
Svelte 5 Web Component
A basic example on how to create web components in svelte 5
Create a second vite config
vite.webcomponents.config.ts
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [
svelte({
compilerOptions: {
customElement: true
}
})
],
build: {
lib: {
entry: 'src/lib/web-components.js',
name: 'MyWebComponents',
fileName: 'my-web-components',
formats: ['iife']
},
rollupOptions: {
output: {
inlineDynamicImports: true
}
},
cssCodeSplit: false,
outDir: 'dist-webcomponents'
}
});
Modify package.json to include new build script
package.json
{
"scripts": {
"build:webcomponents": "vite build --config vite.webcomponents.config.ts",
}
}
Create web component
src/lib/Component.wc.svelte
<svelte:options customElement="my-component" />
<script>
let { name = 'world', children } = $props();
</script>
<h1>Hello {name}!</h1>
{@render children()}
Create entry file for web components
src/lib/web-components.ts
export { default as Component } from './Component.wc.svelte';
Build the web components
pnpm build:webcomponents
Web components will be built to dist-webcomponents.
Use the web component
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="dist-webcomponents/my-web-components.iife.js"></script>
</head>
<body>
<my-component name="Svelte"></my-component>
</body>
</html>
Related snippets
QuickJS sandbox
A basic example on how to run user provided code in a sandbox in the browser with svelte
Get License from package.json
How to get and show the projects license from package.json
Kiwi schema
How to use Kiwi schema
Timelock encryption
Timelock encryption allows you to encrypt data that can only be decrypted after a certain time