Member-only story
How to Use Webpack Module Federation in React
Build micro-frontend architectures with ease
Module Federation is an excellent tool for constructing a micro-frontend architecture in React applications. I will show you how to use it in a step-by-step guide to building a Host-Remote pattern micro-frontend in React.
Why a Micro Frontend?
Micro-frontends help us break large frontend applications into smaller independent applications or modules that can be built and deployed at their cadence.
Doing this using Module Federation allows us to combine the applications at run time in the client’s browsers and eliminate build-time dependencies and coordination, allowing the teams building these applications to develop at scale.
Getting started
You can follow along with the final code found here: https://github.com/rautio/react-micro-frontend-example
We are building two applications: host
and remote
.
The host
app is the “main” app and remote
is a sub-app plugging into it.
Module Federation does support treating the host
as a remote and making the architecture peer-to-peer if it fits your use case. More on this later.
We’re going to use create-react-app
to simplify the initial steps.
In your root directory:
npx create-react-app hostnpx create-react-app remote
This will create two apps for you:
host/remote/
Dependencies
Within each host/
and remote/
run:
npm install --save-dev webpack webpack-cli html-webpack-plugin webpack-dev-server babel-loader
This will install wepback and the dependencies we need for our webpack configuration.
Webpack Module Federation is only available in version 5 and above of webpack.
Host App
We are going to start with our webpack configuration
Create a new webpack.config.js
file at the root of host/
: