Skip to content

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

  1. Install required dependencies:

    pnpm add webpack module-federation-plugin
    
  2. 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

  1. Shared Redux Store:

  2. Use a single Redux store shared across applications.

  3. Event-Based Communication:

  4. Use custom events to communicate between different Micro Frontends.

  5. Shared Context Providers:

  6. 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);
}