In this post we will review the steps to create a module federation using NX
What is NX?
What is Module Federation?
We can see a module federation as a "live" remote import of a library. The module federation includes:
Host: the main web server the browser is connecting to.
Remote: the module web server that the host is importing a library from.
The general idea is to have a microservice approach to the front-end architecture, allowing independent update of each microservice.
Creation Steps
Well it is working, but you will get many warnings.
Don't panic.
Step 1 - Create a new Nx workspace
npx create-nx-workspace@latest my-nx-workspace
- Select Minimal starter
- Try the full Nx platform? … NO! This will use NX Cloud
cd my-nx-workspace
npm install --save-dev @nx/react
nx g @nx/react:app shop --bundler=webpack --style=css
- Would you like to add routing to this application? No
- Which linter would you like to use? … eslint
- E2E test runner? None
- Which port? 4200
nx serve shop
Open browser on http://localhost:4200, and verify it is working.
Press Ctrl+C on the NX command to stop and continue to the next step.
Step 2 - Convert shop into a Module Federation host
nx g @nx/react:host shop --bundler=webpack
- Which stylesheet format would you like to use? … CSS
- Which test runner? None
- Which bundler? webpack
Recheck everything is still running
nx serve shop
Open browser on http://localhost:4200, and verify it is working.
Step 3 - Create Remote App
nx g @nx/react:remote cart --host=shop --style=css --bundler=webpack
In the first terminal window run the remote:
nx serve cart
In the second terminal window run the host:
nx serve shop
Final Note
We have reviewed the steps to create a module federation.
This is just a simple tutorial, but in real life it is much complex. You need to handle cases where the remote is down, proxy AJAX requests from the remote, handle CORS, mismatch dependencies and version and more.
Bottom line, avoid this architecture whenever possible, and use it only if you have to for a very complex infrastructure that has high maintenance costs.
No comments:
Post a Comment