1. Deconstructing the Request:
- Goal: Design a micro-frontend federation system.
- Language: TypeScript-first (strong typing is paramount).
- Core Requirements:
- Codify Shared Contracts: How do apps agree on APIs? (Types, interfaces, schemas).
- Runtime Isolation: How do we prevent CSS/JS clashes? (Shadow DOM, IFrames, specific bundler plugins).
- Dependency Dedupe: How do we avoid loading React 18 times? (Module Federation, shared scopes).
2. High-Level Architecture Strategy:
- The "Host" vs. "Remote" pattern is the industry standard (popularized by Webpack Module Federation).
- TypeScript-first implies we need a separate package or mechanism for sharing types. Runtime federation is usually JS-heavy, so I need to bridge the gap to TS.
- Isolation needs a concrete implementation choice (Shadow DOM is the most common for Custom Elements based MFes).
- Dedupe relies heavily on the build tool (Vite or Webpack) and semantic versioning.
3. Designing the Layers:
-
Layer 1: The Contract (The "Shared Kernel")
- We need a way to define what a remote exposes.
- It's not just code; it's types.
- Idea: A separate npm package (monorepo workspace) containing interfaces and generic component types.
- Key abstraction:
RemoteDefinition.
-
Layer 2: The Runtime Core (The "Shell")
- The Host application needs a loader.
- It needs to handle the lifecycle (load, mount, unmount).
- It needs to enforce isolation.
-
Layer 3: The Build System (Federation)
- Need to configure the bundler to share dependencies (React, etc.) effectively.
- Use
@module-federation (likely Vite or Webpack based).
4. Fleshing out specific implementations:
5. Drafting the Code Structure (Mental Draft):
- Package
@org/types: Define HostConfig, RemoteConfig.
- Package
@org/utils: A helper to wrap remotes in Shadow DOM (optional but good for demo).
- App: Host: Uses the Federation Runtime to load remotes.
- App: Remote (e.g., Checkout): Exposes a component.
6. Refining the TypeScript-First Approach:
- The biggest pain point in MF is typing the remotes from the host side.
- Solution: The host shouldn't just import "any". It should import a typed definition that is generated or defined in the shared contract package.
- Let's use a type-safe loader function.
7. Step-by-Step Implementation Plan:
- Contracts Package: Define the interfaces.
- Federation Config (Vite/Webpack): Show the deduplication setup.
- Runtime Wrapper (Isolation): Create a generic Web Component wrapper that handles Shadow DOM and version checking.
- Usage Example: Host consuming Remote.
8. Self-Correction/Review during drafting:
- Critique: Is Module Federation enough?
- Correction: It handles code loading, but not UI isolation. I must explicitly add Shadow DOM logic or mention iframes. I will choose Shadow DOM + Custom Elements for a "modern" approach.
- Critique: How to handle version mismatches gracefully?
- Correction: Implement a semantic version check in the runtime loader or rely on the bundler's
singleton property. I'll focus on the bundler config for this.
9. Writing the Response:
- Intro: Set the stage (Monorepo context).
- Step 1: Contracts. Define
ExposedComponent and SemanticVersion.
- Step 2: Runtime Core. Create a
MicroFrontendLoader. This needs to handle the async nature of Federation. Use Generics heavily.
- Step 3: Isolation. Create a
IsolatedElement mixin or class using Shadow DOM.
- Step 4: Dependency Deduping. Show the
ModuleFederationPlugin (or Vite equivalent) config, emphasizing singleton: true.
- Step 5: The Glue. How the Host actually calls it type-safely.
10. Final Polish:
- Ensure all code snippets are valid TypeScript.
- Add comments explaining why specific patterns are used (e.g., why
StrictOmit or why eager: false).
- Focus on the "Architecture" aspect, not just code dumping.
(Self-Correction during code writing): I should probably use module-federation with Vite as the example, as it's currently the trendiest and Typescript-friendliest, but standard Webpack is the bedrock. I will write the config generically enough or stick to a standard TS implementation pattern that applies to both, perhaps leaning on the types of the configuration rather than the specific plugin syntax to remain tool-agnostic but "TS-first". Actually, showing a specific federation.config.ts is better.
Let's build the solution.
- Core Type:
RemoteDefinition<Props, API>.
- Dedupe: Shared scope strategy.
- Isolation: Shadow DOM wrapper.
(Drafting the response - following the structure generated in step 9).
This design outlines a TypeScript-First Micro-Frontend Architecture using Module Federation. It prioritizes type safety across boundaries, strictly enforces runtime isolation via Shadow DOM, and optimizes bundle size through semantic versioning and shared dependency scopes.
Architecture Overview
- Contracts Package (
@org/contracts): A dedicated npm package holding shared TypeScript interfaces, Zod schemas (for runtime validation), and Semantic Version ranges.
- Shell (Host): The runtime orchestrator. It discovers remotes and provides shared context.
- Remotes (MFEs): Independently deployable applications built as standard Web Components to ensure framework agnosticism and isolation.
- Federation Config: A typed configuration generator to enforce dependency deduping.
1. The Contracts Layer (Codified Shared Contracts)
Instead of sharing code logic, we share data shapes. This package is a dev-dependency for all MFEs.
packages/contracts/src/types.ts
// Define strict interfaces for communication
export interface UserContext {
id: string;
permissions: string[];
theme: 'light' | 'dark';
}
export interface CartItem {
productId: string;
quantity: number;
}
// The Contract a Remote must satisfy to be mounted
export interface MicroFrontendContract {
mount: (container: HTMLElement, props: RemoteProps) => void;
unmount: (container: HTMLElement) => void;
}
export interface RemoteProps {
userContext: UserContext;
eventBus: EventBus;
}
packages/contracts/src/events.ts
// Type-safe event bus definition
type EventMap = {
'cart:updated': { items: CartItem[] };
'user:logout': void;
};
export interface EventBus {
emit<E extends keyof EventMap>(event: E, payload: EventMap[E]): void;
on<E extends keyof EventMap>(event: E, handler: (payload: EventMap[E]) => void): void;
}
2. The Build System (Dependency Dedupe)
We use a typed Module Federation configuration to ensure that common libraries (React, Vue, Utils) are shared effectively without version conflicts.
tools/federation.config.ts
import { ModuleFederationPlugin } from '@module-federation/enhanced'; // or webpack
import deps from './package.json';
// Helper to strict-type shared config
type SharedConfig = Record<string, { singleton: boolean; requiredVersion: string; eager?: boolean }>;
export const createFederationConfig = (name: string, exposes: Record<string, string>) => {
// Define shared libraries with strict versioning
const shared: SharedConfig = {
react: { singleton: true, requiredVersion: deps.dependencies.react },
"react-dom": { singleton: true, requiredVersion: deps.dependencies["react-dom"] },
// Shared utility logic (if necessary)
"@org/utils": { singleton: true, requiredVersion: deps.dependencies["@org/utils"] },
};
return new ModuleFederationPlugin({
name,
filename: 'remoteEntry.js',
exposes,
shared,
// Runtime type checking shared scope
runtimePlugins: ['./src/runtime/version-check-plugin.ts']
});
};
Runtime Version Check (Concept):
If requiredVersion does not match the loaded version, the build should fail or log a harsh warning in dev mode, preventing runtime crashes due to API mismatches.
3. The Runtime Core (Isolation & Hydration)
To ensure isolation, we wrap every Remote in a Shadow DOM. This prevents CSS bleeds. To ensure type safety, we wrap the loading logic in a Generic Loader.
shell/src/loader/MountPoint.ts
import type { MicroFrontendContract, RemoteProps } from '@org/contracts';
export class MicroFrontendMountPoint extends HTMLElement {
private remoteInstance: MicroFrontendContract | null = null;
private shadow: ShadowRoot;
constructor() {
super();
// HARD ISOLATION: Shadow DOM encapsulates styles
this.shadow = this.attachShadow({ mode: 'open' });
}
async loadRemote(url: string, scope: string, module: string) {
try {
// Dynamic Import via Module Federation runtime
const container = await import(/* webpackIgnore: true */ url);
await container.init(__webpack_share_scopes__.default);
const factory = await container.get(scope);
const Module = factory();
// Type assertion ensures the loaded module matches the Contract
this.remoteInstance = Module as MicroFrontendContract;
} catch (e) {
console.error(`Failed to load remote: ${scope}`, e);
}
}
mount(props: RemoteProps) {
if (this.remoteInstance) {
this.remoteInstance.mount(this.shadow, props);
}
}
disconnectedCallback() {
if (this.remoteInstance) {
this.remoteInstance.unmount(this.shadow);
}
}
}
customElements.define('mfe-mount-point', MicroFrontendMountPoint);
4. The Remote Implementation (TS-Strict)
The remote application implements the contract exactly. It does not mount itself to document.body directly; it waits for the Shell to tell it where to go.
remotes/checkout/src/bootstrap.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import type { MicroFrontendContract, RemoteProps } from '@org/contracts';
import { CheckoutApp } from './App';
// Implementation of the Contract
const CheckoutRemote: MicroFrontendContract = {
mount: (container, props: RemoteProps) => {
// Styles injection into Shadow DOM (requires specific bundler config for CSS)
const styleTag = document.createElement('style');
styleTag.textContent = `/* CSS Content */`;
container.appendChild(styleTag);
const root = createRoot(container);
root.render(
<React.StrictMode>
<CheckoutApp {...props} />
</React.StrictMode>
);
// Store cleanup reference if needed
(container as any)._root = root;
},
unmount: (container) => {
const root = (container as any)._root;
if (root) root.unmount();
}
};
export default CheckoutRemote;
remotes/checkout/federation.config.ts
export default {
name: 'checkout_remote',
exposes: {
'./Component': './src/bootstrap.tsx',
},
// ... shared config
};
5. Host Consumption (The Glue)
The Shell uses the types to strictly pass context.
shell/src/App.tsx
import { MicroFrontendMountPoint } from './loader/MountPoint';
import type { RemoteProps, EventBus } from '@org/contracts';
const eventBus: EventBus = {
emit: (e, p) => console.log(`Event: ${e}`, p),
on: (e, h) => { /* subscribe logic */ }
};
export const ShellDashboard = () => {
const mountRef = useRef<MicroFrontendMountPoint>(null);
useEffect(() => {
const load = async () => {
if (mountRef.current) {
await mountRef.current.loadRemote('http://localhost:3001/remoteEntry.js', 'checkout_remote', './Component');
const props: RemoteProps = {
userContext: { id: '1', permissions: ['read'], theme: 'dark' },
eventBus
};
mountRef.current.mount(props);
}
};
load();
}, []);
return (
<div className="shell-layout">
<h1>Dashboard</h1>
{/* Web Component usage */}
<mfe-mount-point ref={mountRef}></mfe-mount-point>
</div>
);
};
Summary of Features
- Codified Contracts:
MicroFrontendContract interface forces the remote to expose mount and unmount. EventMap ensures the host and remote speak the same event language.
- Runtime Isolation:
- JS: Module Federation creates separate scopes.
- CSS/Styles: Shadow DOM (
this.attachShadow) prevents global CSS pollution.
- Dependency Dedupe: The
shared configuration object in the build step marks react and react-dom as singletons. If the Shell loads React 18.2, and the Remote requests 18.0, the Shell shares the 18.2 instance, ensuring only one React runtime exists in memory.