React Micro-Frontends with Vite
I've found Vite to be an absolutely amazing alternative to Create-React-App, in every single way possible. I see no reason to go back to using CRA.
Ok, but why, and I thought this was about micro-frontends. You are correct.
At work we use CRA for pretty much all our React apps, except for our micro-frontend (MFE) app, without any ability to customise the configurations with CRA and no desire to use a barely maintained hacky way of doing so, I threw together a proof-of-concept MFE using the latest versions of React, TypeScript and Vite.
I had the whole thing up and running in no time. The hardest part of course is the MFE proxy component in the parent app, you need to load in the remote apps manifest file, which by the way, Vite generates the best manifest for consumption and the only configuration needed is to enable manifest generation (manifest: true
), but I digress.
The challenge was, if you navigate to page that uses a MFE you need to load in said MFE's assets. Should be easy, just append a script tag to the pages head
. You do however need to add an id
attribute to said script
and check that it's been appended before re-fetching the assets.
The lifecycle looks something like:
- Navigate to page with a MFE
- Proxy component fetches the manifest
- Manifest is read and a
script
is appended - The MFE's main entry is loaded
But what if the user (or in some cases the app itself) does something to trigger a re-render between steps 2 and 3?
You would need to either cancel the original process that is fetching and appending the script
or implement a check to see if the script hasn't been appended and the manifest isn't being fetched.
If you are thinking that's a lot of work for something that you could just as easily build into the app itself or as a component library to pull in as a dependency, and while that is valid, there are a few reasons why we went with this approach.
It's a lot faster to update something in the MFE, push it and merge it without interfereing with anything in the parent app.
For example, in a multi-team situation where two teams are implementing a feature (or fixing something) in the parent app and one team wants to deploy while the other has just started merging in their feature branches and aren't ready to deploy, you now need to wait to deploy your changes.
There is however a right time and place to use a MFE. Don't abuse it and use it for small components. For example, don't turn a button or menu into a micro-frontend, you could however implement an entire header/nav or sidebar as a micro-frontend.