patternjavascriptMajor
Webpack 5 Module Federation: sharing code across micro-frontends at runtime
Viewed 0 times
Webpack 5
module federationwebpack 5micro-frontendremoteEntryshared singletonruntime sharing
Error Messages
Problem
Multiple independent Webpack apps need to share components, utilities, or vendor libraries without duplicating bundles or requiring a monorepo build step.
Solution
Use Webpack 5 ModuleFederationPlugin. One app exposes modules, another app consumes them at runtime.
// Host (consumer) webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
shop: 'shop@http://localhost:3001/remoteEntry.js',
},
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
}),
],
};
// Remote (shop) webpack.config.js
new ModuleFederationPlugin({
name: 'shop',
filename: 'remoteEntry.js',
exposes: { './Cart': './src/Cart' },
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
});
// In host app
const Cart = React.lazy(() => import('shop/Cart'));
// Host (consumer) webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
shop: 'shop@http://localhost:3001/remoteEntry.js',
},
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
}),
],
};
// Remote (shop) webpack.config.js
new ModuleFederationPlugin({
name: 'shop',
filename: 'remoteEntry.js',
exposes: { './Cart': './src/Cart' },
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
});
// In host app
const Cart = React.lazy(() => import('shop/Cart'));
Why
Module Federation moves code sharing from build-time to runtime. Each remote is an independently deployed app. The host fetches module manifests and loads chunks on demand via dynamic import, avoiding the need to rebuild all apps when one changes.
Gotchas
- All federated apps must use Webpack 5 — mixing Webpack 4 and 5 is unsupported
- Mark shared packages as singleton: true for React to prevent multiple instances
- requiredVersion should match semver ranges to avoid version mismatches at runtime
- Async boundaries are required: wrap federated imports in React.Suspense
- remoteEntry.js URL is hardcoded at build time — use environment variables for flexibility
Context
Building micro-frontend architectures where teams deploy independent apps that compose at runtime
Revisions (0)
No revisions yet.