This content originally appeared on Level Up Coding - Medium and was authored by Vitalii Shevchuk
Even your grandma will be able to build react micro frontend with NX
Content
- Intro
- Proof of Concept
- Building Microfrontend applications
- Implementing the shareable state
- Github Link
- Conclusion
- Learn More
Intro
Some time ago, I have posted the article Building ⚛️ React Micro Frontends Monorepo with NX in 5 min
Building ⚛️ React Micro Frontends Monorepo with NX
It was a time when NX didn’t support micro frontends preset generators for React, only for Angular. Many people complained about bugs and issues with this custom implementation. Now, I would like to share some awesome news, that support came true and I am thrilled to present you with an updated version of the article. We are building React micro frontends with state management, wait for it…not in 5 min, … wait for it…, but in 2 min 😜
Let’s not waste our time and jump straight into the tutorial.
Before we start, join me to get more content:
Join Medium with my referral link - Vitalii Shevchuk
Proof of Concept
Usually, when we build micro frontend applications, we create one shell application (or host, container) and multiple remote micro frontend applications. In our example, we will have 2 applications: the shell and remote. Additionally, we will have a shared library — a shared data context. Both shell and remote will consume the state from the shared data context. Shared data context will hold the state — the counter, the shell will have a button to increment the state, and remote — the button that decrements the counter state. The final result will look like this:
Building Microfrontend applications
We will start with generating monorepo.
npx create-nx-workspace mf-react-state --preset=empty
Then, let’s add React dependencies
yarn add --dev @nrwl/react
Now, we can generate our shell and remote React applications
nx g @nrwl/react:host shell --remotes=remote
If we want to generate multiple remotes, we will specify the names of applications with the comma separator, like:
--remotes=remote1, remote2
💡Note: if you encounter the error during running the command, make sure you are using the latest version of nx cli, you can also try to update the monorepo with the next commands: yarn add -D @nrwl/cli , nx migrate latest and nx migrate --run-migrations
That's pretty much it, now you can run the application:
nx serve shell --open --devRemotes=remote
Implementing the shareable state
The next step is to add the shareable library, we need to run the command
nx g @nrwl/react:library shared/data-context
Let’s go to the mf-react-state/libs/shared/data-context/src/lib/shared-data-context.tsx and add the counter state:
import { createContext, useState } from 'react';
export interface SharedDataContextProps {
children: JSX.Element;
}
export const DataContext = createContext<Record<string, any>>({});
export function DataProvider({ children }: SharedDataContextProps) {
const [counter, setCounter] = useState(1);
return (
<DataContext.Provider value={{ counter, setCounter }}>
{children}
</DataContext.Provider>
);
}
export default DataProvider;
Make sure you exported the DataContext and DataProvider from mf-react-state/libs/shared/data-context/src/index.ts
export { DataProvider, DataContext } from './lib/shared-data-context';
We need to share our library as a singleton. In order to do it, we need to modify the module-federation.config.jsfiles both in the shell and remote:
In mf-react-state/apps/shell/module-federation.config.js
// Core libraries such as react, angular, redux, ngrx, etc. must be
// singletons. Otherwise the applications will not work together.
const coreLibraries = new Set(['react','react-dom','react-router-dom','@mf-react-state/shared/data-context']);
module.exports = {
name: 'shell',
remotes: ['remote'],
shared: (libraryName, defaultConfig) => {
if (coreLibraries.has(libraryName)) {
return defaultConfig;
}
// Returning false means the library is not shared.
return false;
},
};
And in mf-react-state/apps/remote/module-federation.config.js the same.
const coreLibraries = new Set(['react','react-dom','react-router-dom','@mf-react-state/shared/data-context']);
module.exports = {
name: 'remote',
exposes: {
'./Module': './src/remote-entry.ts',
},
shared: (libraryName, defaultConfig) => {
if (coreLibraries.has(libraryName)) {
return defaultConfig;
}
// Returning false means the library is not shared.
return false;
},
};
Then we need to add the provider to our shell app mf-react-state/apps/shell/src/app/app.tsx
Cool, the last step is when we need to consume the context state in the shell and remote app.
In mf-react-state/apps/shell/src/app/nx-welcome.tsx
And in mf-react-state/apps/remote/src/app/app.tsx
Congrats 🎉, if you type fast enough, you can finish this app in 2 min, or in 30 sec if you pull it from the repo 😅
Github Link
GitHub - Vitashev/mf-react-state
Conclusion
Well, I am happy that guys from NX continue to improve their product and make us, a frontend developers’ life easier. I imagine the time when we will have salvation from writing the code, and just generate whatever we want from the command line 😁. Anyways, before Elon Mask will release his robot, we will still need to do some coding work, unfortunately. Dear friends, if you enjoyed the article, make others see it, clap 👏 and it will show up to 10 people more. Follow to stay with me.
Get an email whenever Vitalii Shevchuk publishes.
Learn More
- 🔥 Top 3 React Tricks Pros 😎 like to Use to Reduce the Size of a Component
- How to Deploy and Host Angular 🅰️ Micro Frontend for FREE Using Firebase 🔥
- 🥺 Building the NFT Instagram app with React and Thirdweb
🔥 Building ⚛ React Micro Frontends Monorepo with State Management using NX in 2 min 😅 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-06-14T11:58:48+00:00) Building ⚛ React Micro Frontends Monorepo with State Management using NX in 2 min. Retrieved from https://www.scien.cx/2022/06/14/building-%e2%9a%9b-react-micro-frontends-monorepo-with-state-management-using-nx-in-2-min/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.