Micro Frontends: Module Federation
Module Federation is a webpack feature that allows sharing code between multiple applications at runtime.
Module Federation is a webpack feature that allows sharing code between multiple applications at runtime, making it a key enabler for Micro Frontends.
Why Use Module Federation?
- Share code dynamically without redeploying the entire application
- Enable independent deployments
- Reduce duplication of shared libraries
Setting Up Module Federation
-
Install required dependencies:
-
Configure
webpack.config.js
:const ModuleFederationPlugin = require("webpack").container.ModuleFederationPlugin; module.exports = { plugins: [ new ModuleFederationPlugin({ name: "app1", remotes: { app2: "app2@http://localhost:3002/remoteEntry.js", }, shared: { react: { singleton: true }, "react-dom": { singleton: true }, }, }), ], };
Example Usage
In your main application (host):
Micro Frontends: Shared State in Micro Frontends
Sharing state across Micro Frontends can be achieved using libraries like Redux, Zustand, or even custom context solutions.
Approaches to Shared State
-
Shared Redux Store:
-
Use a single Redux store shared across applications.
-
Event-Based Communication:
-
Use custom events to communicate between different Micro Frontends.
-
Shared Context Providers:
- Create a shared context provider that can be consumed by different Micro Frontends.
Example
import { createContext, useContext } from "react";
const GlobalStateContext = createContext();
export function GlobalStateProvider({ children }) {
const state = { user: { name: "John Doe" } };
return (
<GlobalStateContext.Provider value={state}>
{children}
</GlobalStateContext.Provider>
);
}
export function useGlobalState() {
return useContext(GlobalStateContext);
}