| | |

Svelte 98 ๐Ÿงก Micro-Frontend Architecture with Svelte Custom Elements

โฑ๏ธ Estimated read: 7 min | |

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

ConfigurationProperty
customElementSet to true or string name
tagString tag name
shadow"open" or "closed"

Interop Patterns

DirectionMechanism
Host to SvelteAttributes (Props)
Svelte to HostCustomEvent
Style InjectionCSS 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

PitfallWhy It HappensFix
Style leakageNo Shadow DOMEnable shadow: "open"
Prop type errorAttributes are stringsUse explicit type conversion
Event missingNot a CustomEventUse new CustomEvent()
Over-stylingHardcoded CSSUse 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

ItemValue
Directivesvelte:options customElement
Style scopeShadow DOM
OutputWeb Component class
PropsDOM Attributes
EventsCustomEvent
CommunicationStandards-based API

Key takeaways:

  • Use standard Web Components. The customElement option 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.

Was this helpful?


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!