Vite + Module Federation is AMAZING!
Learn how to create scalable frontend applications using Vite and Module Federation.
October 27, 2024
Table of contents
- Introduction
- Step 1: Create the host and remote applications
- Step 2: Config the remote application
- Step 3: Config the host application
- Step 4: Build and test the application
- Conclusion
- References
Introduction
Personally, I love the simplicity of Vite, so for this post we will try to explain in a simple, step by step way how we can modularize our frontend applications to use a microfrontend architecture.
The microfrontend architecture allows us to divide parts of our application into individual and autonomous modules, allowing frontend teams the same level of flexibility and speed that microservices provide to backend teams.
For this post I will use Bun so it will be a dependency to keep in mind if you want to follow it step by step.
You can install Bun by following the instructions in this link.
Step 1: Create the host and remote applications
First, create the host and remote React applications using Vite CLI.
Step 2: Config the remote application
Now, letβs install the necessary dependencies and add the Module Federation plugin to the remote application.
Create a new folder and file for the component that will be exposed by the remote application.
Add the following code to the ExampleComponent.tsx
file.
In the vite.config.ts
file, add the following configuration to expose the component.
Update the package.json scripts to build and preview the remote application using the 4174 port.
Build and preview the remote application.
If you open the browser and go to http://localhost:4174/remoteEntry.js
, you should see the remote entry file that will be consumed by the host application.
Step 3: Config the host application
Now, in other terminal, go to the host application and install the necessary dependencies and add the Module Federation plugin.
In the vite.config.ts
file, add the following configuration to consume the remote component.
Update the package.json scripts to build and preview the host application using the 4173 port.
Add the following code to the App.tsx
file to consume the remote component.
Step 4: Build and test the apllication
Build and preview the host application.
If you open the browser and go to http://localhost:4173/
, you should see the remote entry file that will be consumed by the host application!
Conclusion
Vite + Module Federation is a powerful combination that allows us to create scalable frontend applications and can be very easy to implement!
I hope you found this guide useful, that you can start using it in your projects and that you can share it with your colleagues.
If you have any questions, feel free to ask via social media.
Happy coding!