Svelte 98 ๐งก Micro-Frontend Architecture with Svelte Custom Elements
Micro-frontend architecture enables organizations to scale development by breaking monolithic web applications into smaller, independent, and deployable units. Svelte is an exceptional candidate for this pattern because its compiler-based approach produces lightweight, framework-agnostic Web Components. By using the customElement option, Svelte components can be distributed as standard HTML elements that function seamlessly in React, Vue, Angular, or even plain vanilla JavaScript applications.
This chapter details how to transform standard Svelte components into Web Components using the svelte:options directive. We will explore how to manage prop synchronization, handle custom events across framework boundaries, and architect a strategy for shared state in a multi-framework environment. We will cover the configuration, the integration patterns, and the lifecycle considerations necessary to build a robust micro-frontend ecosystem.
Key point: The svelte:options customElement directive instructs the Svelte compiler to package a component as a standard Web Component, allowing it to be consumed via HTML tags and bridged to host frameworks through native standard attributes and custom events.
Why exists
The technology-agnostic requirement. Enterprises often have legacy systems built in older frameworks; micro-frontends allow them to introduce modern Svelte components without rewriting the entire host application.
The team autonomy requirement. Different teams can own different parts of the application (e.g., checkout vs. navigation) and deploy their components independently without worrying about the framework versions or build pipelines of other teams.
The isolation requirement. By using Shadow DOM, Custom Elements provide CSS encapsulation, ensuring that styles from the host application do not leak into the component and vice versa, solving the “CSS specificity war.”
The bundle optimization requirement. Svelteโs small runtime overhead makes it ideal for micro-frontends where multiple components are loaded on the same page, preventing the “heavy framework” tax often seen with larger libraries.
The version stability requirement. Because each Web Component is self-contained, a team can upgrade a specific micro-frontend to a newer version of Svelte without requiring a coordinated upgrade across the entire organization.
The interoperability requirement. Web Components are a browser standard, ensuring that micro-frontends remain functional regardless of future framework shifts in the host application or the broader web ecosystem.
a. Configuring Custom Elements
To convert a Svelte component into a Custom Element, you use the svelte:options directive. This tells the compiler to expose the component as a class that registers itself with the customElements registry. You must provide a custom tag name to prevent naming collisions.
<svelte:options customElement="my-widget" />
<script>
let { title = "Default" } = $props();
</script>
<div class="card">
<h1>{title}</h1>
</div>
Once compiled, you can simply include the output JavaScript file in any HTML page and use <my-widget title="Hello World"></my-widget>. The Svelte compiler handles the transformation of props into observed attributes and ensures that the component responds to changes in the DOM.
b. Bridging State (Props and Events)
Bridging state between a host application and a Svelte Custom Element requires understanding the boundary between DOM attributes and JavaScript properties. Attributes are always strings; therefore, Svelte converts them into the types defined by your component props.
<svelte:options customElement="user-profile" />
<script>
let { username, onUpdate } = $props();
function trigger() {
const event = new CustomEvent("user-changed", { detail: { username } });
dispatchEvent(event);
}
</script>
<button onclick={trigger}>Update {username}</button>
Communication from the component back to the host is handled via native CustomEvent dispatching. The host framework listens for these events using standard DOM APIs or its own synthetic event system. This remains standard across every framework, making it the most reliable way to communicate across boundaries.
c. Orchestration and Shadow DOM
Shadow DOM is enabled by default in Svelte custom elements. It creates a scoped document fragment, isolating styles. While this prevents style leaks, it also prevents global styles (like Bootstrap or Tailwind) from reaching your component.
<svelte:options customElement={{
tag: "styled-component",
shadow: "open"
}} />
<style>
div { color: var(--theme-color, blue); }
</style>
<div>Scoped Content</div>
To allow host styles to penetrate the component, you can use CSS Custom Properties (variables). By defining variables in the host CSS, the Svelte component can read them, effectively creating a “Theme API” for your micro-frontend that maintains the benefits of isolation while allowing necessary styling flexibility.
Complete Example Session
// ============================================
// PART 1: COMPONENT DEFINITION
// ============================================
// CounterWidget.svelte
<svelte:options customElement="counter-widget" />
<script>
let { count = 0 } = $props();
function increment() { count++; }
</script>
<button onclick={increment}>Count: {count}</button>
// ============================================
// PART 2: HOST INTEGRATION (HTML)
// ============================================
// index.html
<counter-widget count="5"></counter-widget>
<script src="dist/counter-widget.js"></script>
// ============================================
// PART 3: REACT INTEROP
// ============================================
// App.jsx
function App() {
return <counter-widget count={10} />;
}
// ============================================
// PART 4: EVENT LISTENER
// ============================================
// main.js
const widget = document.querySelector('counter-widget');
widget.addEventListener('count-change', (e) => {
console.log('New count:', e.detail);
});
This sequence covers the compilation of a Svelte component into a widget, its usage in raw HTML, its integration into React, and the cross-framework communication via events.
Quick Reference
Options Table
| Configuration | Property |
|---|---|
customElement | Set to true or string name |
tag | String tag name |
shadow | "open" or "closed" |
Interop Patterns
| Direction | Mechanism |
|---|---|
| Host to Svelte | Attributes (Props) |
| Svelte to Host | CustomEvent |
| Style Injection | CSS Variables |
Best Practices
โ Do This:
// Use hyphenated names for custom tags
<svelte:options customElement="app-nav" /> // โ
// Expose internal state via custom events
dispatchEvent(new CustomEvent("data")); // โ
// Use CSS variables for theme injection
color: var(--primary-color); // โ
// Prefix event names for clarity
"my-app-event" // โ
โ Don’t Do This:
// Use single word names (invalid)
<svelte:options customElement="widget" /> // โ
// Try to access the DOM parent directly
window.parent.document; // โ
// Rely on global CSS
.global-class { color: red; } // โ
// Use reserved event names
"click" // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Style leakage | No Shadow DOM | Enable shadow: "open" |
| Prop type error | Attributes are strings | Use explicit type conversion |
| Event missing | Not a CustomEvent | Use new CustomEvent() |
| Over-styling | Hardcoded CSS | Use CSS Custom Properties |
Real-World Examples
1. Registration
<svelte:options customElement="user-card" />
2. Advanced config
<svelte:options customElement={{ tag: "my-card", shadow: "open" }} />
3. Dispatching
dispatchEvent(new CustomEvent("submit", { detail: form }));
4. Prop definition
let { initialValue = 0 } = $props();
5. Theme hook
:host { border: 1px solid var(--border-color); }
6. External listener
el.addEventListener('submit', (e) => { ... });
7. Attribute observed
el.setAttribute('count', '10');
8. React wrapping
// React can render WC directly
<my-element data={val} />
9. Lifecycle hook
$effect(() => { /* mounted */ });
10. Shadow DOM access
const root = el.shadowRoot;
Visual
The Micro-Frontend Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HOST APPLICATION (React/Vue/Angular) โ
โ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โ โ <app-nav /> โ โ <cart-widget /> โ โ
โ โโโโโโโโฌโโโโโโโโโโโ โโโโโโโโโโฌโโโโโโโโโโ โ
โ โ โ โ
โ (Attributes/Props) (CustomEvents) โ
โ โ โ โ
โ โโโโโโโโผโโโโโโโโโโโ โโโโโโโโโโผโโโโโโโโโโ โ
โ โ Svelte Element โ โ Svelte Element โ โ
โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Shadow DOM Isolation
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ GLOBAL SCOPE โ
โ .button { color: red; } โ
โ โ โ
โ SHADOW ROOT (Encapsulation) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Styles inside cannot affect global โ โ
โ โ Global styles cannot affect inside โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Component Lifecycle Bridge
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DOM: connectedCallback โโโบ Svelte Mount โ
โ โ
โ DOM: attributeChanged โโโบ Svelte Update โ
โ โ
โ DOM: disconnectedCallback โโบ Svelte Destroy โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Directive | svelte:options customElement |
| Style scope | Shadow DOM |
| Output | Web Component class |
| Props | DOM Attributes |
| Events | CustomEvent |
| Communication | Standards-based API |
Key takeaways:
- Use standard Web Components. The
customElementoption compiles Svelte components into native elements, ensuring interoperability across all frameworks. - Isolate styles. Shadow DOM prevents CSS leaks, but rely on CSS Custom Properties to allow themes to be passed from the host application.
- Attributes as interface. Since custom element attributes are passed as strings, ensure your logic correctly handles casting for numbers and booleans.
- Use
CustomEvent. Native browser events are the language of cross-framework communication; avoid library-specific event systems for MFE boundaries. - Independent deployments. Micro-frontends allow teams to move at their own pace; maintain strict API contracts via props and events to keep them decoupled.
Remember: Micro-frontends are an architectural strategy to manage complexity, not a reason to introduce inconsistency. By treating every Svelte Custom Element as a pure, self-contained “Widget” that communicates strictly via standard attributes and events, you create a system that is robust, scalable, and resilient to the churn of host-framework changes.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!