Webpack Module Federation

Webpack's Module Federation is a new feature that was introduced in Webpack5 with the intent of having multiple independent separate builds should form a single application, such that they can be shared and deployed exclusively.

Let us walk through a simple example, assume there are two apps:

How do we configure webpack to enable federation?

The comic-app is basically exposing one of it's components that basically fetches the random XKCD comic, let us say the component name is FethComic.jsx the webpack config for federation in the comic app would look like:

plugins: [
new ModuleFederationPlugin({
name: "comic",
filename: "remoteEntry.js",
exposes: {
"./FetchComic": "./FetchComic.jsx",
},
// always use the higher version found
shared: [
{
react: {
singleton: true, // only a single version of the shared module is allowed
eager: true,
},
"react-dom": {
singleton: true,
eager: true,
},
},
],
}),
];

The home-app consumes the exposed component and the config would look like:

plugins: [
new ModuleFederationPlugin({
name: "home",
filename: "remoteEntry.js",
remotes: {
comic: `[email protected]://localhost:1338/remoteEntry.js}`, // 1338 is the comic app port in this example
},
shared: [
{
react: { singleton: true, eager: true },
"react-dom": { singleton: true, eager: true },
},
],
}),
];

Now, the home-app can dynamically import the remote component and use it like anyother!

import React, { useState, lazy, Suspense } from "react";

const FetchComic = lazy(() => import("comic/FetchComic"));

<Suspense fallback={() => "Meow"}>
<div>
<FetchComic />
</div>
</Suspense>;

Here is the complete working application:

If you notice ^ the dir structure is bit different compared to "regular" apps, as we have eager sharing, we would see a Uncaught Error: Shared module is not available for eager consumption error if we don't bootstrap the application, more details at troubleshooting.

Was discussing alternatives to bootstrap with my friend Nikhil Motiani who has been pawing hard at webpack federation.

You can also fork the repo from wepack-module-fedaration-sample to get a taste of it.

Feel free to share this article. You may as well ping me on Twitter.

Published