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:
- comic-app: Standalone react app which fetches random comics from XKCD [remote-app].
- home-app: Standalone react app that uses comic-app's exposed component [host-app].
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",
},
shared: [
{
react: {
singleton: true,
eager: true,
},
"react-dom": {
singleton: true,
eager: true,
},
},
],
}),
];
- The configuration is exposing
FetchComic.jsx
with exposes
attribute so that it can be consumed
by the home-app
. react
and react-dom
are the shared dependencies across the applications.
The home-app
consumes the exposed component and the config would look like:
plugins: [
new ModuleFederationPlugin({
name: "home",
filename: "remoteEntry.js",
remotes: {
comic: `comic@https://localhost:1338/remoteEntry.js}`,
},
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