Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Webpack with Frameworks

Module Federation

Learn webpack 5 Module Federation: hosts, remotes, exposes, shared dependencies and version negotiation, with a config walkthrough and the pitfalls of micro-frontends.

Normally an application is built as one unit: all its code is bundled together at build time. Module Federation, introduced in webpack 5, lets separately built and separately deployed applications share code at run time. One app (the host) loads modules from another app (a remote) over the network as if they were local, and both can share dependencies such as React so that only one copy is downloaded.

This is the basis of many micro-frontend architectures: a team owns the checkout page, another owns the product catalogue, each deploys independently, and a shell app stitches them together in the browser. This lesson explains the vocabulary, the configuration and the trade-offs. It builds on code splitting and dynamic imports.

Webpack cannot run on this site. The configs are read-only. The runnable blocks are Node.js stand-ins: a host and remote with an init/get contract, and a shared-scope version picker. They show the logic, not webpack's implementation.

The vocabulary

  • Container: the small entry file webpack builds for a federated app (usually remoteEntry.js). It exposes an init function and a get function.
  • Remote: an app that exposes modules for others to consume.
  • Host: an app that consumes modules from remotes. An app can be both.
  • Exposes: the list of modules a remote makes public.
  • Shared: dependencies both sides can use from one common copy.
flowchart LR
  H["Host (shell)<br/>app1.example.com"] -- "loads remoteEntry.js" --> R["Remote (checkout)<br/>checkout.example.com"]
  H -- "import('checkout/Cart')" --> R
  H -. "shared scope" .- R

The host fetches the remote's container at run time and imports its exposed modules.

Configuration

The remote exposes a component:

JavaScript
// checkout/webpack.config.js (read-only example)
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  output: { publicPath: 'auto' },
  plugins: [
    new ModuleFederationPlugin({
      name: 'checkout',
      filename: 'remoteEntry.js',
      exposes: {
        './Cart': './src/Cart.jsx',
      },
      shared: {
        react: { singleton: true, requiredVersion: '^18.2.0' },
        'react-dom': { singleton: true, requiredVersion: '^18.2.0' },
      },
    }),
  ],
};

The host points at the remote's container:

JavaScript
// shell/webpack.config.js (read-only example)
new ModuleFederationPlugin({
  name: 'shell',
  remotes: {
    checkout: 'checkout@https://checkout.example.com/remoteEntry.js',
  },
  shared: {
    react: { singleton: true, requiredVersion: '^18.2.0' },
    'react-dom': { singleton: true, requiredVersion: '^18.2.0' },
  },
});

And uses it like any dynamic import:

JSX
const Cart = React.lazy(() => import('checkout/Cart'));

Because the host's entry must finish loading shared modules before anything runs, federated apps normally use an async boundary: index.js contains only import('./bootstrap'), and the real start-up code lives in bootstrap.js. Without it you get the error "Shared module is not available for eager consumption".

The container contract

A container behaves like a tiny module registry. The host calls init(sharedScope) to hand over shared dependencies, then get('./Cart') to receive a factory for the exposed module.

Node.js Stand-in: a host loading from a remote container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Shared dependencies and versions

If both apps bundle React, the user downloads it twice, and two copies of React in one page break hooks. The shared option solves that: each side registers the versions it has in a shared scope, and the first side to need a library gets the best match.

Important options:

Option Meaning
singleton: true Only one version may be loaded. Required for libraries with global state (React, router).
requiredVersion The semver range this app needs.
eager: true Include in the initial chunk (avoid it; it removes the sharing benefit).
strictVersion: true Fail instead of warn when versions do not satisfy the range.

The stand-in picks the highest registered version that satisfies a simple caret range. Real webpack uses full semver.

Node.js Stand-in: choose a shared version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For a singleton, the shell's pick (18.3.1) is used by everyone, and catalog, which asked for React 17, would get a console warning, or an error with strictVersion. This is why micro-frontends need shared upgrade policies for core libraries.

Dynamic remotes

Hard-coding a remote URL means rebuilding the host when the remote moves. Instead, define the remote as a promise that decides the URL at run time, for example from a config endpoint or a feature flag:

JavaScript
remotes: {
  checkout: `promise new Promise((resolve) => {
    const url = window.__REMOTES__.checkout;       // injected by the server
    const script = document.createElement('script');
    script.src = url;
    script.onload = () => resolve(window.checkout);
    document.head.append(script);
  })`,
},

Trade-offs

Module Federation is powerful, but it is not free.

  • Run-time coupling. A broken deploy of a remote breaks the host. Plan fallbacks and error boundaries around remote imports.
  • Versioning. Exposed components are an API. Changing props breaks consumers; use contracts and tests.
  • Complexity. Debugging across apps, local development with several servers and shared type definitions all take effort.
  • Performance. Waterfalls: host, then remoteEntry.js, then the chunk. Prefetch remote entries where you can.

Choose it when independent teams and independent deploys are a real need. For a single team, plain code splitting is simpler. Federation is also available outside webpack through plugins for Vite and Rspack, which is relevant when you consider alternatives.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a host do in Module Federation?

    The host loads remote containers and imports their exposed modules. An app can also be a remote at the same time.
  2. 2. Why mark react as singleton in shared?

    Libraries with global state must exist once. singleton makes federation load a single version for all apps.
  3. 3. What does the async boundary (import('./bootstrap')) solve?

    Shared modules must be negotiated before use. An async boundary gives webpack time to do that before your code runs.
  4. 4. Which is a real downside of federating many micro-frontends?

    Because remotes are loaded at run time, host and remotes depend on each other's availability and contracts.

Summary

  • Module Federation lets independently built apps share modules and dependencies at run time.
  • Remotes expose, hosts list remotes, and shared negotiates one copy of common libraries.
  • Use an async bootstrap boundary, singletons for stateful libraries and error boundaries around remote loads.
  • Adopt it for independent teams and deploys, not for convenience in small apps.

Next: Upgrading from Webpack 4 to 5