There are many articles in DZone and videos on the internet on Micro Frontends. So I’ll skip the details and jump to the article. This article is about demonstrating the development of Micro Frontends using vanilla web components. I consider two Micro Frontends that are deployed independently of each other to two sub-domains and using different code repositories. These frontends are then assembled as one SPA. I’ll then discuss the communication between the frontends and then present a working online demo of this SPA. 

The SPA – The Desired Result

The screenshot of the SPA for this demo is:

where two micro frontends, productsApp and cartApp, are assembled as one SPA. The user can select one or more products, add them to the cart and then view their selections in the cart. The two frontend apps are deployed independently of each other with their own sub-domains. The code for the two apps are also in separate repositories.

Micro Frontend #1 – Products App

The  productsApp.html  uses a web component, ProductsComp with a custom element like:

 <products-comp id="productsApp" ></products-comp> 

The source for  products-comp.js  is:

where, for brevity of discussion, I am not using Shadow DOM feature of web components. All the code for this frontend is stored in its own repository.

and deployed to its own sub-domain:
https://mapteb.github.io/micro-frontends-using-webcomponents/productsApp.html 

Micro Frontend #2 – Cart App

The   cartApp.html  uses a web component, CartComp with a custom element like:

 <cart-comp id="cartApp" ></cart-comp> 

The source for   cart-comp.js   is:

All the code for this frontend is stored in its own repository.

and deployed to its own sub-domain:
https://ns-code.github.io/micro-frontends-cartapp/cartApp.html

Frontends Assembly – SPA

The two frontends are assembled as one SPA in this index.html:

where custom elements from the two frontends are used. The JavaScript files for the two frontends are also imported. When the user selects one or more fruits and adds them to the cart, the ProductsComp dispatches an event called selectedFruits. The JavaScript listener in index.html receives it and dispatches the data to another custom event called cartLoaded. The Cart App listener  then receives this event data and displays it as items in the  cart.

Here is the online demo for this SPA.

Conclusions

Modern browsers supported vanilla web components and event handling mechanisms are shown to provide a simple way to get started with micro frontends. The online demo hints at the many touted benefits of using micro frontends – multiple teams working in parallel and independently supporting complex SPAs.

Related Works

Interested readers can checkout the following:
1. https://micro-frontends.org/ (online demo)
2. https://github.com/kito99/micro-frontends-demo
3. https://luigi-project.io/
4. https://piral.io/ 



Source link

Write A Comment