In Dixons Carphone, we are rebuilding our platform with microfrontend architecture. It means investigating the ways how to achieve the best user and developer experience possible. This is a series about our journey.
What is microfrontend
I will not repeat what was already written somewhere else. Should you wonder what microfrontend is, take a short break with the excellent article written by Vinci Rufus and then come back.
Microfrontends: An approach to building Scalable Web Apps
When we talk about building modern Web Apps, Single Page Apps is what comes first to mind.
We want to be able to load our micro apps from the registry by URL. Therefore we need to make NodeJS able to import modules from some URL.
Loader hooks to the rescue
Since Node 11 there is an experimental API which makes you able to change NodeJS module resolution behaviour. As the API is really experimental, it is changing with Node 12 (API), which I will use in the examples.
Let’s show some code. We want to be able to do this:
It is just a simple Express server which renders tiny application. The file loads lodash from unpkg.com and
app from own HTTP server:
Note that we import
react-dom/server. We don't have it installed next to the application and in future, when we will be bundling the application we will mark those “platform” dependencies like externals. It will be provided by a renderer application.
Let's finally show some code which does the magic (check the comments in the code for explanation):
What is not solved yet
This module loading is really just an experiment. We need to make this work with Next.js which we use in our wrapper application that renders page layouts.
We did not have to solve these areas yet:
- whitelisting domains to download from
- redownload script on change — if there is file already downloaded, it does not download it again
- Make it work with Next.js (via Webpack plugin)
In the next article, I will show how we solved the integration to Next.js via Webpack plugin. Let me know, what do you think about our idea and about importing modules from some URLs in general.
Would you do micro-frontends in a better way?