This content originally appeared on Level Up Coding - Medium and was authored by Vitalii Shevchuk
Building ⚛️ React Micro Frontends Monorepo with NX in 5 min
In this tutorial, you will build React Micro Frontend without the hustle
Content
- Before Intro
- Intro
- Proof of Concept
- Setting up Monorepo Project
- Configuring Shell application
- Configuring Remote application
- Connecting Micro Frontends
- Github link
- Conclusion
- Learn More
Before Intro
Hey World 🌎 Before we start, I want to say thank you to everyone, who shares some love ❤️ with my blog, we are 833 Followers (02/22/2022) already, and we are growing fast. All the posts — are free and aim to raise the curiosity of web development. The energy comes from your clap 👏, comment 💬 or subscribe.
I am Ukrainian 🇺🇦 and everyone knows what is going on now, if not, Putin sent the whole of its army to destroy my country and my people. If you want to support Ukraine, and want to kick away the Hitler of 21st century. Show a voice on your social media. You can also find the donation link below.
1. Donations through NBU (National Bank of Ukraine) — https://lnkd.in/g32YRZPp
2. Nova Ukraine, a non-profit focused on humanitarian aid — https://novaukraine.org/
3. Support Ukrainian military efforts — https://lnkd.in/gAp6WqKk
Intro
Nx, thanks to its libraries, solves all major problems that micro frontend faces: like sharing the components and state between micro frontends. Moreover, Nx supports Angular Micro Frontend schematics out of the box, that let you generate Angular Micro Frontend applications using a command line. You can find the tutorial here:
- 🔥 Building Angular Micro Frontend with NgRx state sharing and NX cli
- 🔥 Build a Beautiful TikTok Clone with Angular and Micro Frontend
Proof of Concept
We want to keep all the NX features and at the same time, use React framework instead. The stack is similar to the projects above:
- ⚛️ React — top 1 frontend framework of all times;
- NX — monorepo generator, that let you scale the application like Google;
- Webpack Module Federation — let you combine real-time builds into a single application;
The micro frontend application will consist of a shell app and a remote app. Shell is a container application that will inject remote micro frontend:
The remote app — is hosted separately and exposes the component, which will be accessible from the shell app.
Let’s keep it simple and jump straight into the implementation🏃
Setting up Monorepo Project
Setting up monorepo has never been that easy.
- Create monorepo workspace with empty setup named mf-react :
npx create-nx-workspace --preset=empty mf-react
cd mf-react
2. Installing all react dependencies:
npm install -D @nrwl/react
3. Generating shell app:
nx g @nrwl/react:app shell
4. And lastly, generating the remote app:
nx g @nrwl/react:app remote
Configuring Shell application
- First, let’s open mf-react/apps/shell/src and make a few changes here:
- Rename main.tsx into bootstrap.tsx ;
- Create index.ts with
import('./bootstrap');
It will set up an asynchronous boundary, that will split out the code of a larger chunk to avoid additional round trips and improve performance. You can read more in detail here:
2. Next, we need to tune the mf-react/apps/shell/project.json :
- “main”: “apps/shell/src/index.ts”
- “webpackConfig”: “apps/shell/webpack.config.js” — use custom webpack configuration;
- “hmr”: false — It will avoid reloading loop of async remote app importing;
The complete project.json looks like this:
3. And finally, let’s create webpack.config.js in mf-react/apps/shell
The important detail is adding the proxy :
proxy: {
'http://localhost:3000': 'http://localhost:3000',
},
Hack Alert: The reason for it, is that during async module loading, webpack will try to load the remote entry from http://localhost:3000 (remote app address). And when it is not ready, it will start to redirect to http://localhost:5000 (shell app address) and throw the error, that chunk doesn’t exist under that host. We need to force the compiler to resolve the remote script strictly from the remote host http://localhost:3000. It is hacky, so don't consider such an implementation in production. In production, we will use the domain name instead http://localhost:3000 and it will work without any issues.
Configuring Remote application
The remote app configuration is very similar to the shell, with the only difference of exposing the component in the module federation plugin.
- In mf-react/apps/remote/srcrename main.tsx into bootstrap.tsx . Create index.ts and import the module.
import('./bootstrap');
2. In mf-react/apps/remote/project.json we need to change two things: “webpackConfig”: “apps/remote/webpack.config.js” and entry point “main”: “apps/remote/src/index.ts”
3. Now, let’s create webpack.config.js in mf-react/apps/remote/ and add configuration:
‘./RemoteEntry’: ‘./src/app/components/RemoteEntry’, here we specify the path to the component that we are going to expose, let’s create it.
4. In mf-react/apps/remote/src/app/components/RemoteEntry.tsx create the exposed component:
function RemoteEntry() {
return (
<div>
<h3>Remote Entry</h3>
</div>
);
}
export default RemoteEntry;
5. And finally, add RemoteEntry into the mf-react/apps/remote/src/app/app.tsx
import RemoteEntry from './components/RemoteEntry';
export function App() {
return <RemoteEntry></RemoteEntry>;
}
export default App;
Connecting Micro Frontends
- First, let’s start the remote app under port 3000:
nx serve --project=remote --port=3000
2. Then, we will need to create a type for our remote module as our compiler doesn't know about its existence. Create mf-react/apps/shell/declarations.d.ts and add the type:
declare module 'remote/RemoteEntry';
3. Here it comes the last step, adding the remote module into the shell app. In mf-react/apps/shell/src/app/app.tsx :
import React, { Suspense } from 'react';
const RemoteEntry = React.lazy(() => import('remote/RemoteEntry'));
export function App() {
return (
<>
Shell App
<Suspense fallback={<div>Loading...</div>}>
<RemoteEntry></RemoteEntry>
</Suspense>
</>
);
}
export default App;
Here we can see that our remote module successfully imported 🎉
Github Link
You can find the full project setup here:
GitHub - Vitashev/mf-react: React Micro Frontends Monorepo with Nx
Conclusion
In the end, you will have a fully functioning micro frontend monorepo. And even more, you can use all the features of NX, including sharing libraries: UI components and state between micro frontends. You can find the whole feature specification here. If you want to learn how to share the state between react micro frontends, let’s collect 1000 👏 and I will iterate over it. And as usual, if you learned something new, follow me on medium and Twitter 😊
- Get an email whenever Vitalii Shevchuk publishes.
- Join Medium with my referral link - Vitalii Shevchuk
Learn More
- 🔥 How Micro Frontend changes the Future of Angular?
- 🔥 Building Angular Micro Frontend with NgRx state sharing and NX cli
- 🔥 Build a Beautiful TikTok Clone with Angular and Micro Frontend
Building ⚛️ React Micro Frontends Monorepo with NX was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Vitalii Shevchuk
Vitalii Shevchuk | Sciencx (2022-02-28T14:14:06+00:00) Building ⚛️ React Micro Frontends Monorepo with NX. Retrieved from https://www.scien.cx/2022/02/28/building-%e2%9a%9b%ef%b8%8f-react-micro-frontends-monorepo-with-nx/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.