Recently, it seems that micro front-end has become the standard configuration for front-end engineers. From single-SPA to Qiankun, various micro front-end architecture solutions are emerging one after another. That night, while scrolling through Github, I noticed a new micro front end framework, the open source MicroApp from JD Retail, which claims to require no adjustments to the subapp’s rendering logic like the two frameworks mentioned above, or even webPack configuration. Another success that caught my attention was its use of the web-Components concept! Let’s find out!

1. Small dishes after dinner – Web Components 🍡

Web Components is a native implementation of edible Web Components, which you can think of as Components developed under frameworks like VUE and React. The difference is that components developed under this standard can be used directly under HTML without relying on other third-party libraries.

In other words: Some of the apis provided by modern browsers make it possible to create reusable components that do not depend on any framework, and are not constrained by the framework

The main features are as follows:

  • Use Custom Elements to customize labels
  • Use shadow DOM for style isolation
  • Templates and Slots for component expansion (not in this installment)

So how does Web Components create a component? Let’s take a look at this demo in action

1.1 practice

For the Web Components practice, I found a demo on Github. As shown in the figure below, suppose A page is independently developed by three different teams. Team A is responsible for the overall display of the red area, while team B and TEAM C are responsible for the blue and green areas (shown in the red area). How do they achieve this?

Let’s take a look at the code example for the demo, which can essentially be understood as defining a component green-recos

Through the figure above, let’s analyze this code, mainly including the following information:

  • How do I customize elements? : Via Api:window.customElementsTo define the registered instance
  • How do I define a component instance? : By inheritanceHTMLElementDefine an instance class
  • How does it communicate with the outside world? : By creating aCustomEventFrom defining a new event and then passingaddEventListenerTo listen to andelement.dispatchEvent()To distribute events
  • How do I control the lifecycle of a component? : mainly includes these lifecycle functions in the following order: πŸ‘‡

Constructor -> attributeChangedCallback(which is called when an element is added, deleted, or modified) -> connectedCallback (when an element is first inserted into the document DOM) Called) -> disconnectedCallback(called when the Custom Element is removed from the document DOM) ‘

Development:

  • The demo can fork the warehouse: πŸ“¦

1.2 About Compatibility

πŸ‘¨πŸŽ“ Ah Le: It is said that web Component is not very compatible. How to do?

You can see the figure above πŸ‘†, most browsers support the new version, if you want to work with older versions, don’t be afraid to introduce polyfill to solve the compatibility problemwebcomponents/polyfills

You can also use the Strong WebComponentsReady event to tell if the WebComponents have been successfully loaded

1.3 About Style Conflicts

If you want to develop Components based on Web Components and are worried about style conflicts between Components, you can use Shadow DOM to solve the problem. This is similar to the scoped processing of defining Components in Vue

Shadow DOM: Also known as the Shadow DOM, it can attach a hidden, independent DOM to an element. The following figure shows the MDN official introduction

How to develop a web Component based component that hangs in #shadow-root?

We can see from the illustration above that the attachShadow method is used in comparison to the example from the previous section. What is it?

Attach a shadow root to any element using attachShadow. It takes as a parameter a configuration object that has a mode property. When mode is true, it means that the Shadow DOM can be obtained using JavaScript methods within the page

🌲 Read more:

  • The current engineer encountered a Web Component

1.4 Attention to Detail

Ah, Mr. Tree, can I use a custom Component developed by Web Component in vUE?

That’s fine, but it’s important to note that Vue Component development is similar to custom elements. If we don’t do a little “manipulation”, Vue will treat your Web Component development as a Component within its own framework. So we need to configure ignoredElements. Here is an example from the Vue website

If you want to learn more about Web Component development, check out this open source Component library

  • Making: xy – the UI

2 Mrcio-app

Accidentally detour, back to business, talk about today’s protagonist: Micro-app

We need to integrate a micro application on the base without the following three elements πŸ‘‡ :

  • Register child applications in the dock
  • Lifecycle functions need to be defined in the subapplication
  • Modify webPack packaging for microapplications

Although the cost of transformation is not particularly high, but can you minimize the intrusion of the source code?

Mrcio-app is a minimalist route, as long as the modification of a lost code can be achieved micro-application integration, known as the current market to connect to the micro front end of the lowest cost solution. So how does it do that?

2.1 the principle

Essentially micro-app is a micro front-end architecture based on class WebComponent + HTML Entry implementation

Official Introduction: Through the connectedCallback function of the user-defined element micro-app life cycle, listen to the element being rendered, load the HTML of the child application and convert it to THE DOM structure, recursively query all static resources such as JS and CSS and load them, set element isolation, and intercept all dynamically created script, link and other tags. Extract the tag content. After the loaded JS is processed by the plug-in system, it is put into the sandbox to run, and the STYLE isolation of CSS resources is carried out. Finally, the formatted elements are put into micro-app, and the micro-APP element is finally rendered as a micro-front-end sub-application. During rendering, the developer bound lifecycle functions are executed for further operations.

  • The Entry file of the micro application is loaded. On the one hand, the static resource JS and CSS files of the micro application are fetched. On the other hand, the DOM of the micro application is rendered

  • Webcomponent-like: we looked at two features in the previous section on learning about web components: CustomElement, which enables usto create custom tags, and ShadowDom, which enables usto create a ShadowDom that supports isolation styles and element isolation. What is the WebComponent class that was first mentioned? The essence is to use the CustomElement combined with the custom ShadowDom to achieve the basic consistent WebComponent function

In other words: let micro front-end micro application achieve true sense of componentization

2.2 Great mechanics

Micro-app has several mechanisms that I find very cool:

  • You don’t have to pre-define lifecycle functions for each micro-application like Qiankun. For example:created,mountedEtc., but another way, when you integrate in the base, the base can be directly defined, also can be global monitoring. As shown below.

In the property configuration in the figure above, name is the micro application name configuration, URL is the child application page address configuration, and others are the definition of each lifecycle function

  • Automatic completion of resource address: When we load microapplications on the base, when microapplications involve loading images or other resources, if the access path is relative address, we will find that static resources will be completed with the domain address where the base application is located, resulting in resource loading errors. Micro-app can complete the relative addresses of static resources of sub-applications into absolute addresses, which solves the above problems

2.3 practice

2.3.1 demo to fit

It’s also easy to get started. Take the vuE2 app as an example and refer to the Github documentation for details. There’s no repetition here

Let’s see what the integration looks like through the official online vue microapplication Demo

In the console, we can see that after loading the micro app “vue2” on the base, after rendering the custom tag micro-app, there is a complete subapp Dom, which is similar to the feeling of iframe. Then, the CSS style of the subapp is prefixed micro-app[name=vue2]. The name attribute of the label is used to add a prefix to each style, confining the style influence of the child application to the current label area, and avoiding style conflicts among different microapplications. This is the default quarantine mechanism for micro-apps

Ah le classmate: tree jam, how does he achieve this element isolation?

Let me explain and move on to source code analysis

2.3.2 Process of rendering microapplications

The main flow chart of rendering micro application process can refer to the official provision, mainly including the following process

  • The FETCH child applies HTMl: The FETCH takes the HTMl, transforms it into a DOM structure and recursively processes each child element, making appropriate processing source links for different elements

The purpose is to extract microapplication links and scripts, bound to the style scope. Finally implement the microapplication style hanging inmicro-app-headThe core source code is as follows

Scopecss is configured in the micro application initialization definition (enabled by default), and scopedCSS is invoked to handle the dom. This method binds the micro application to the CSS scope

I see in the source code that scoped_css mainly treats several cSSrules differently

Ah Heng: Tree jam, what is Css Rule?

This is an old concept, CSSRule represents a CSS rule. A CSS stylesheet contains a set of CSSRule objects that represent rules. There are several different types of CSSRule, and you can differentiate between the following types of general CSSRule in the Micro-app

  • CSSRule.STYLE_RULE: A general style rule
  • CSSRule.MEDIA_RULE: CSSΒ @mediaRules for querying media properties
  • CSSRule. SUPPORTS_RULE: CSS@supportDifferent style rules can be defined depending on the browser’s support for CSS features

Finally, append the converted style content to the micro-app-head

Ah Heng: Tree jam, you said that micro-app isolation element supports shadowDom?

Yes, the default style isolation mentioned above is invalid if shadowDOM is turned on. And compatibility will be poor

Here’s a truncated version: About Mircro-app passedWeb Component + shadowDOMThe implementation of sub-application initialization definition, specific source code you can read about the framework source codemicro_app_elementThe definition ofSource link

In essence, the

tag is not a WebComponent until shadowDom is enabled

3 At the end

About JS sandbox (Sandbox) and the implementation mechanism of data communication, etc., in the back to expand with children’s shoes to share

Previous popular articles πŸ“– :

  • These Node Open Source tools are worth Owning (2)
  • Developing visual Data Large screens from 0 to 1 (Top)
  • Developing visual Data Large screens from 0 to 1 (Bottom)
  • Construction of the Front-end Knowledge System of Tree Jam (PART ONE)
  • Construction of the Front-end Knowledge System of Tree Jam (Part ii)
  • Talk about everyday collaboration tools for front-end development
  • Babel configuration is stupid to read
  • How to better manage apis
  • The interviewer is asking you about Node
  • Front-end engineering those things
  • Did you learn BFF and Serverless
  • Front-end o&M deployment things

Hello, I am 🌲 tree jam, please drink a cup 🍡 remember three consecutive oh ~

1. Remember to click “like” after reading, there is πŸ‘ motivation

2. Pay attention to the public number front of those fun, with you to talk about the front of the fun

3. The article is featured on Github frontendThings thanks to Star✨