Module Federation
Master module federation for micro-frontend architectures — runtime module sharing across independently deployed applications, shared dependency negotiation, version compatibility strategies, and performance optimization for federated systems.
When to Use
- Multiple teams deploy independent frontend applications that compose into a unified experience
- Shared component libraries are duplicated across micro-frontends, inflating total download size
- A monolithic frontend needs to be incrementally decomposed without a full rewrite
- Independent deploy cadences require runtime integration rather than build-time bundling
- Shared dependencies (React, design system) are loaded multiple times across micro-frontends
- A plugin or extension system needs to load third-party code at runtime
- A/B testing requires swapping entire feature modules at runtime without redeployment
- The design system team wants to push updates to all consuming applications without each one rebuilding
- Legacy and modern applications need to coexist and share components
- Build times are unacceptable because all micro-frontends rebuild together in a monorepo
Instructions
Configure the host application. The host (shell) application declares which remote modules it consumes and which dependencies it shares:
// webpack.config.js (host/shell)
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'shell',
remotes: {
catalog: 'catalog@https://catalog.example.com/remoteEntry.js',
checkout: 'checkout@https://checkout.example.com/remoteEntry.js',
account: 'account@https://account.example.com/remoteEntry.js',
},
shared: {
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
'@company/design-system': {
singleton: true,
requiredVersion: '^3.0.0',
},
},
}),
],
};
Configure remote applications. Each remote exposes specific modules and declares its shared dependencies:
// webpack.config.js (catalog remote)
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'catalog',
filename: 'remoteEntry.js',
exposes: {
'./ProductList': './src/components/ProductList',
'./ProductDetail': './src/components/ProductDetail',
'./SearchBar': './src/components/SearchBar',
},
shared: {
react: { singleton: true, requiredVersion: '^18.0.0' },
'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
'@company/design-system': {
singleton: true,
requiredVersion: '^3.0.0',
},
},
}),
],
};
Load remote modules dynamically. Use dynamic imports with error boundaries for resilient loading:
// In the host application
import { lazy, Suspense } from 'react';
import ErrorBoundary from './ErrorBoundary';
const RemoteProductList = lazy(() => import('catalog/ProductList'));
const RemoteCheckout = lazy(() => import('checkout/CheckoutFlow'));
function App() {
return (
<ErrorBoundary fallback={<FallbackCatalog />}>
<Suspense fallback={<ProductListSkeleton />}>
<RemoteProductList />
</Suspense>
</ErrorBoundary>
);
}
Configure shared dependency versioning. Prevent duplicate React instances while allowing compatible version ranges:
shared: {
react: {
singleton: true, // only one instance at runtime
strictVersion: false, // allow compatible versions
requiredVersion: '^18.0.0',
eager: false, // load asynchronously (default)
},
'lodash-es': {
singleton: false, // multiple versions OK
requiredVersion: '^4.17.0',
},
'@company/utils': {
singleton: true,
version: '2.5.0',
requiredVersion: '>=2.0.0 <3.0.0',
},
}
Implement dynamic remote loading. For scenarios where remote URLs are determined at runtime (feature flags, environment configuration):
// Dynamic remote container loading
async function loadRemote(scope: string, module: string, url: string) {
await loadScript(url);
const container = (window as any)[scope];
await container.init(__webpack_share_scopes__.default);
const factory = await container.get(module);
return factory();
}
function loadScript(url: string): Promise<void> {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.onload = () => resolve();
script.onerror = reject;
document.head.appendChild(script);
});
}
// Usage
const ProductList = lazy(() => loadRemote('catalog', './ProductList', getRemoteUrl('catalog')));
Set up health checks and fallbacks. Remote modules can fail to load due to network issues or deployment problems:
class FederationErrorBoundary extends React.Component {
state = { hasError: false, retryCount: 0 };
static getDerivedStateFromError() {
return { hasError: true };
}
handleRetry = () => {
this.setState(prev => ({
hasError: false,
retryCount: prev.retryCount + 1,
}));
};
render() {
if (this.state.hasError) {
if (this.state.retryCount < 3) {
return (
<div>
<p>Failed to load module. </p>
<button
</div>
);
}
return this.props.fallback;
}
return this.props.children;
}
}
Monitor federation performance. Track remote entry load times and shared dependency negotiation overhead:
// Measure remote module load time
const start = performance.now();
const RemoteModule = await import('catalog/ProductList');
const duration = performance.now() - start;
performance.measure('federation:catalog:ProductList', {
start,
duration,
});
Details
How Module Federation Works
At build time, each federated application generates a remoteEntry.js manifest file that describes its exposed modules and shared dependency requirements. At runtime, the host loads the remote's manifest, negotiates shared dependencies (using the highest compatible version available), and lazily loads the requested module. The shared scope ensures that singleton libraries like React are loaded once and reused across all federated applications, preventing multiple React instance errors and reducing total download size.
Version Negotiation Algorithm
When multiple federated applications declare different versions of a shared dependency, the runtime selects the highest version that satisfies all requiredVersion constraints. If no single version satisfies all constraints, the module that cannot be satisfied loads its own bundled version (unless strictVersion: true is set, which throws an error). The singleton: true flag ensures only one version is loaded globally — critical for libraries like React that break with multiple instances.
Worked Example: IKEA Micro-Frontends
IKEA's web platform uses module federation to compose product browsing, cart, and checkout from independent applications maintained by separate teams. The shared dependency configuration ensures a single React instance (40KB) and one design system (60KB) are loaded regardless of how many micro-frontends are active. Each micro-frontend's remoteEntry.js is ~5KB and loads in <50ms. The total overhead of federation versus a monolithic build is approximately 15KB of runtime code, offset by the ability to deploy and cache each micro-frontend independently.
Anti-Patterns
Sharing too many dependencies as singletons. Only libraries that break with multiple instances (React, React DOM, state management) should be singletons. Utility libraries (lodash, date-fns) can safely have multiple versions, and forcing them to singleton creates unnecessary version conflicts.
Missing error boundaries around remote modules. Without error boundaries, a failing remote crashes the entire host application. Every remote module should be wrapped in both an Error Boundary and a Suspense boundary with meaningful fallback UI.
Eager loading all shared dependencies. Setting eager: true on shared dependencies defeats the purpose of async loading. Only set eager on dependencies that must be available synchronously at bootstrap (rare). Default to eager: false.
Tight coupling between host and remotes. If the host directly imports TypeScript types from a remote's source code, the host depends on the remote at build time. Use shared interface packages published to npm, not direct source imports.
Source
Process
- Read the instructions and examples in this document.
- Apply the patterns to your implementation, adapting to your specific context.
- Verify your implementation against the details and edge cases listed above.
Harness Integration
- Type: knowledge — this skill is a reference document, not a procedural workflow.
- No tools or state — consumed as context by other skills and agents.
Success Criteria
- Shared singleton dependencies (React, design system) load exactly once across all micro-frontends.
- Remote modules load within 200ms on broadband connections.
- Failed remote modules display fallback UI without crashing the host application.
- Each micro-frontend can be deployed independently without rebuilding the host.
- The federation runtime overhead is under 20KB gzipped.
1---2name: perf-module-federation3description: Module Federation4metadata:5 source: https://skillmd.com/skills/intense-visions/perf-module-federation6---7# Module Federation89> Master module federation for micro-frontend architectures — runtime module sharing across independently deployed applications, shared dependency negotiation, version compatibility strategies, and performance optimization for federated systems.1011## When to Use1213- Multiple teams deploy independent frontend applications that compose into a unified experience14- Shared component libraries are duplicated across micro-frontends, inflating total download size15- A monolithic frontend needs to be incrementally decomposed without a full rewrite16- Independent deploy cadences require runtime integration rather than build-time bundling17- Shared dependencies (React, design system) are loaded multiple times across micro-frontends18- A plugin or extension system needs to load third-party code at runtime19- A/B testing requires swapping entire feature modules at runtime without redeployment20- The design system team wants to push updates to all consuming applications without each one rebuilding21- Legacy and modern applications need to coexist and share components22- Build times are unacceptable because all micro-frontends rebuild together in a monorepo2324## Instructions25261. **Configure the host application.** The host (shell) application declares which remote modules it consumes and which dependencies it shares:2728 ```javascript29 // webpack.config.js (host/shell)30 const { ModuleFederationPlugin } = require('webpack').container;3132 module.exports = {33 plugins: [34 new ModuleFederationPlugin({35 name: 'shell',36 remotes: {37 catalog: 'catalog@https://catalog.example.com/remoteEntry.js',38 checkout: 'checkout@https://checkout.example.com/remoteEntry.js',39 account: 'account@https://account.example.com/remoteEntry.js',40 },41 shared: {42 react: { singleton: true, requiredVersion: '^18.0.0' },43 'react-dom': { singleton: true, requiredVersion: '^18.0.0' },44 '@company/design-system': {45 singleton: true,46 requiredVersion: '^3.0.0',47 },48 },49 }),50 ],51 };52 ```53542. **Configure remote applications.** Each remote exposes specific modules and declares its shared dependencies:5556 ```javascript57 // webpack.config.js (catalog remote)58 const { ModuleFederationPlugin } = require('webpack').container;5960 module.exports = {61 plugins: [62 new ModuleFederationPlugin({63 name: 'catalog',64 filename: 'remoteEntry.js',65 exposes: {66 './ProductList': './src/components/ProductList',67 './ProductDetail': './src/components/ProductDetail',68 './SearchBar': './src/components/SearchBar',69 },70 shared: {71 react: { singleton: true, requiredVersion: '^18.0.0' },72 'react-dom': { singleton: true, requiredVersion: '^18.0.0' },73 '@company/design-system': {74 singleton: true,75 requiredVersion: '^3.0.0',76 },77 },78 }),79 ],80 };81 ```82833. **Load remote modules dynamically.** Use dynamic imports with error boundaries for resilient loading:8485 ```typescript86 // In the host application87 import { lazy, Suspense } from 'react';88 import ErrorBoundary from './ErrorBoundary';8990 const RemoteProductList = lazy(() => import('catalog/ProductList'));91 const RemoteCheckout = lazy(() => import('checkout/CheckoutFlow'));9293 function App() {94 return (95 <ErrorBoundary fallback={<FallbackCatalog />}>96 <Suspense fallback={<ProductListSkeleton />}>97 <RemoteProductList />98 </Suspense>99 </ErrorBoundary>100 );101 }102 ```1031044. **Configure shared dependency versioning.** Prevent duplicate React instances while allowing compatible version ranges:105106 ```javascript107 shared: {108 react: {109 singleton: true, // only one instance at runtime110 strictVersion: false, // allow compatible versions111 requiredVersion: '^18.0.0',112 eager: false, // load asynchronously (default)113 },114 'lodash-es': {115 singleton: false, // multiple versions OK116 requiredVersion: '^4.17.0',117 },118 '@company/utils': {119 singleton: true,120 version: '2.5.0',121 requiredVersion: '>=2.0.0 <3.0.0',122 },123 }124 ```1251265. **Implement dynamic remote loading.** For scenarios where remote URLs are determined at runtime (feature flags, environment configuration):127128 ```typescript129 // Dynamic remote container loading130 async function loadRemote(scope: string, module: string, url: string) {131 await loadScript(url);132 const container = (window as any)[scope];133 await container.init(__webpack_share_scopes__.default);134 const factory = await container.get(module);135 return factory();136 }137138 function loadScript(url: string): Promise<void> {139 return new Promise((resolve, reject) => {140 const script = document.createElement('script');141 script.src = url;142 script.onload = () => resolve();143 script.onerror = reject;144 document.head.appendChild(script);145 });146 }147148 // Usage149 const ProductList = lazy(() => loadRemote('catalog', './ProductList', getRemoteUrl('catalog')));150 ```1511526. **Set up health checks and fallbacks.** Remote modules can fail to load due to network issues or deployment problems:153154 ```typescript155 class FederationErrorBoundary extends React.Component {156 state = { hasError: false, retryCount: 0 };157158 static getDerivedStateFromError() {159 return { hasError: true };160 }161162 handleRetry = () => {163 this.setState(prev => ({164 hasError: false,165 retryCount: prev.retryCount + 1,166 }));167 };168169 render() {170 if (this.state.hasError) {171 if (this.state.retryCount < 3) {172 return (173 <div>174 <p>Failed to load module. </p>175 <button onClick={this.handleRetry}>Retry</button>176 </div>177 );178 }179 return this.props.fallback;180 }181 return this.props.children;182 }183 }184 ```1851867. **Monitor federation performance.** Track remote entry load times and shared dependency negotiation overhead:187188 ```typescript189 // Measure remote module load time190 const start = performance.now();191 const RemoteModule = await import('catalog/ProductList');192 const duration = performance.now() - start;193194 performance.measure('federation:catalog:ProductList', {195 start,196 duration,197 });198 ```199200## Details201202### How Module Federation Works203204At build time, each federated application generates a `remoteEntry.js` manifest file that describes its exposed modules and shared dependency requirements. At runtime, the host loads the remote's manifest, negotiates shared dependencies (using the highest compatible version available), and lazily loads the requested module. The shared scope ensures that singleton libraries like React are loaded once and reused across all federated applications, preventing multiple React instance errors and reducing total download size.205206### Version Negotiation Algorithm207208When multiple federated applications declare different versions of a shared dependency, the runtime selects the highest version that satisfies all `requiredVersion` constraints. If no single version satisfies all constraints, the module that cannot be satisfied loads its own bundled version (unless `strictVersion: true` is set, which throws an error). The `singleton: true` flag ensures only one version is loaded globally — critical for libraries like React that break with multiple instances.209210### Worked Example: IKEA Micro-Frontends211212IKEA's web platform uses module federation to compose product browsing, cart, and checkout from independent applications maintained by separate teams. The shared dependency configuration ensures a single React instance (~40KB) and one design system (~60KB) are loaded regardless of how many micro-frontends are active. Each micro-frontend's `remoteEntry.js` is ~5KB and loads in <50ms. The total overhead of federation versus a monolithic build is approximately 15KB of runtime code, offset by the ability to deploy and cache each micro-frontend independently.213214### Anti-Patterns215216**Sharing too many dependencies as singletons.** Only libraries that break with multiple instances (React, React DOM, state management) should be singletons. Utility libraries (lodash, date-fns) can safely have multiple versions, and forcing them to singleton creates unnecessary version conflicts.217218**Missing error boundaries around remote modules.** Without error boundaries, a failing remote crashes the entire host application. Every remote module should be wrapped in both an Error Boundary and a Suspense boundary with meaningful fallback UI.219220**Eager loading all shared dependencies.** Setting `eager: true` on shared dependencies defeats the purpose of async loading. Only set eager on dependencies that must be available synchronously at bootstrap (rare). Default to `eager: false`.221222**Tight coupling between host and remotes.** If the host directly imports TypeScript types from a remote's source code, the host depends on the remote at build time. Use shared interface packages published to npm, not direct source imports.223224## Source225226- webpack: Module Federation — https://webpack.js.org/concepts/module-federation/227- Module Federation documentation — https://module-federation.io/228- Zack Jackson: "Module Federation and Micro-Frontends" — https://module-federation.io/blog/229- Micro Frontends in Action — https://micro-frontends.org/230231## Process2322331. Read the instructions and examples in this document.2342. Apply the patterns to your implementation, adapting to your specific context.2353. Verify your implementation against the details and edge cases listed above.236237## Harness Integration238239- **Type:** knowledge — this skill is a reference document, not a procedural workflow.240- **No tools or state** — consumed as context by other skills and agents.241242## Success Criteria243244- Shared singleton dependencies (React, design system) load exactly once across all micro-frontends.245- Remote modules load within 200ms on broadband connections.246- Failed remote modules display fallback UI without crashing the host application.247- Each micro-frontend can be deployed independently without rebuilding the host.248- The federation runtime overhead is under 20KB gzipped.