Enabling Live Reload in Module Federated CRA

By Raj Rajhans -
September 18th, 2021
3 minute read

This is a rather short post describing how to enable hot reload in a module federated CRA. I faced this issue, and couldn’t easily find good solutions, and had to dive a bit deep into webpack docs. So, I thought of writing this post to provide a quick solution in case someone else faces the same issue.

The Problem


Let’s say the CRA app you are working with depends on a federated remote module. And, when you make changes in the remote module, you want your host app (CRA) to reload so as to reflect those changes. Normally, the host app won’t reload since it doesn’t directly know that the remote module has changed. So you will have to reload it manually. This is what we want to fix. It’s not necessary for the host app to be CRA, it can be anything. It was CRA in my case.

The Solution


The solution is pretty straightforward. We’ll do two things -

  1. Configure host app’s webpack dev server to watch for changes in the remote app’s directory.
  2. Configure remote app’s webpack dev middleware to write the bundle files to disk, rather than serving from memory.

The second point will make sure that the changes that happen are written to disk, and then due to the config in first point, host’s app will pick up those changes and trigger a reload.

Modifying host app’s webpack config

Add the following to your host app’s webpack config, which, in my case, is CRA. So I have used CRACO to extend it.

module.exports = {
...
devServer: {
liveReload: true,
watchFiles: [path.resolve(__dirname, '..', 'PATH_TO_REMOTE_APP')],
},
}

Modifying remote app’s webpack config

module.exports = {
...
devServer: {
devMiddleware: {
writeToDisk: true,
},
},
}

With these two small changes, live reload will now work in your module federated app. Whenever you make a change in remote, the host app will reload itself, thus reflecting the changes you did in remote.

Why not Hot Module Replacement?


What we configured was Live Reload, which means that on detecting changes, the host app page will refresh. The next level of this is Hot Module Replacement, wherein the host app won’t need to be reloaded, and the changes will be applied instantly without page refresh. This is great, because it saves even more time.

The issue is that currently HMR doesn’t work with module federation. See this and this issue on webpack repos to understand why.

There is an alternative, though. There is a WIP plugin called “Federated Module Reloading” being worked upon, but it’s still in very early stages. So as of now, live reload will have to suffice.

References


raj-rajhans

Raj Rajhans

Product Engineer @ invideo