Deep Dive into Webpack Module Federation
1. Introduction
Webpack Module Federation is a game-changing feature of Webpack 5 that allows developers to share modules between different applications at runtime. This enables the development of micro frontends, where independent teams can work on different parts of a web application without stepping on each other's toes.
2. Key Concepts
2.1 Module Federation
Module Federation allows multiple builds to form a single application. The core components include:
- Remote Module: A module exposed by another application.
- Host Application: The application that consumes remote modules.
2.2 Dynamic Remote Loading
Modules can be loaded on demand, reducing the initial load time of applications.
2.3 Shared Dependencies
Different applications can share libraries like React or Vue to avoid duplication and save bandwidth.
3. Setup
First, ensure you have Webpack 5 installed in your project. You can create a new project or use an existing one.
npm install webpack webpack-cli --save-dev
Next, create two separate applications: the host and the remote application.
4. Configuration
Configuration is done in the Webpack config files of both applications.
4.1 Host Application Configuration
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
// other configurations...
plugins: [
new ModuleFederationPlugin({
name: "host",
remotes: {
remoteApp: "remote@http://localhost:3001/remoteEntry.js",
},
}),
],
};
4.2 Remote Application Configuration
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
module.exports = {
// other configurations...
plugins: [
new ModuleFederationPlugin({
name: "remote",
filename: "remoteEntry.js",
exposes: {
'./Component': './src/Component',
},
}),
],
};
5. Best Practices
- Keep the shared dependencies to a minimum to avoid version conflicts.
- Use semantic versioning for your micro frontends to maintain compatibility.
- Implement error boundaries in your host application to handle remote module load failures gracefully.
6. FAQ
What is Module Federation?
Module Federation is a feature that allows multiple Webpack builds to share code dynamically, enabling micro frontends.
How do you handle shared dependencies?
Dependencies can be shared by configuring the `shared` option in the Module Federation Plugin.
Can remote modules be loaded from a CDN?
Yes, remote modules can be hosted on a CDN, making them accessible globally.
7. Module Federation Workflow
graph TD;
A[Host Application] -->|loads| B[Remote Module];
B --> C[Shared Dependencies];
C --> D[Render Component];