14. Module Federation and Micro-Frontends
Module Federation is a Webpack feature that enables loading modules from other builds at runtime. It's the foundation of micro-frontend architecture. This module covers Module Federation and micro-frontend patterns.
The key insight is that Module Federation allows independent builds to share code. Teams can deploy independently while sharing common dependencies. This enables micro-frontend architectures at scale. Understanding Module Federation is essential for large-scale frontend development.
This module covers Module Federation setup, micro-frontend patterns, and best practices.
Module Federation
Module Federation allows a Webpack build to load modules from another build. It exposes modules from one build and consumes them from another. This enables micro-frontend architectures where multiple teams deploy independently.
Module Federation works at runtime, loading modules on demand. It handles dependency sharing and versioning. Understanding Module Federation is essential for micro-frontend development.
Try It Yourself: Module Federation
Follow these steps to set up Module Federation.
Step 1: Install dependenciesnpm install --save-dev webpack webpack-cli webpack-dev-server
Step 2: Configure host// webpack.config.js (host)<br>const { ModuleFederationPlugin } = require(<strong><code>webpack).container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: host,
remotes: {
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js',
},
shared: [react, react-dom],
}),
],
};
Step 3: Configure remote// webpack.config.js (remote)<br>const { ModuleFederationPlugin } = require(<strong><code>webpack).container;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: remoteApp,
filename: remoteEntry.js,
exposes: {
./Button: ./src/Button,
./Header: ./src/Header,
},
shared: [react, react-dom],
}),
],
};
Step 4: Use the remote// host/src/App.js<br>const Button = React.lazy(() => import(<strong><code>remoteApp/Button));
Try It Yourself: Create a micro-frontend architecture with two apps. Share components between them.
Knowledge Check
Ready to test your understanding of 14. Module Federation and Micro-Frontends?