8

image.png

Foreword: Recently, there is a feeling 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 in an endless stream. That night, when I was reading github, I noticed a new micro front-end framework, from the open source MicroApp Jingdong Retail, which claims that there is no need to adjust the rendering logic of the sub-applications like the two frameworks mentioned above, and there is no need to modify webpack. Configuration. There is another success that caught my attention: it put the concept of web-components to use! Let us find out!

1. After a meal-Web Components 🍵

As we all know, Web Components implementing web components that can be taken. You can understand it as similar to components developed under frameworks such as 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: The API provided by some modern browsers makes it possible for us to create a reusable component without relying on any framework, without being restricted by the framework

Mainly include the following features:

  • Use custom elements to customize tags
  • Use shadow DOM for style isolation
  • Use templates and slots to achieve component expansion (not expanded in this issue)

How does Web Components create a component? Let's take a look at the following demo practice

1.1 Practice

web components the practice of 0610a73409b6c6, I found a demo on github. As shown in the figure below, assuming that a page is developed independently by three different teams, team A is responsible for the overall display function of the red area, team B and team C are responsible for the blue and green areas (displayed in the red area), then they How is it achieved?
image.png

Let's take the function of the green area as an example, take a look at the demo code example, which can be understood essentially as defining a component green-recos

carbon (27).png

Through the above figure, we will analyze this code, which mainly includes the following information:

  • How to customize elements? : Define the registered instance through the defined method in Api: window.customElements
  • How to define a component instance? : Define an instance class by inheriting HTMLElement
  • How to communicate with the outside world? : Create a CustomEvent customize a new event, and then use addEventListener to monitor and element.dispatchEvent() to distribute the event
  • How to control the life cycle of components? : Mainly include these life cycle functions, the order is as follows 👇

    constructor (element initialization) -> attributeChangedCallback (called when the element is added, deleted, or modified its own attributes) -> connectedCallback (called when the element is inserted into the document DOM for the first time) -> disconnectedCallback (when the custom element is removed from the document DOM When deleted, it is called)`

expand:

  • For the specific demo, you can fork this warehouse: link 📦

1.2 About compatibility

👨‍🎓 Ah Le: Shujiang, I heard that the web component compatibility is not very good? What's up?

image.png
You can see the picture above 👆, most browsers support the new version. If you want to be compatible with the old version, don’t panic, you can solve the compatibility problem by introducing polyfill webcomponents/polyfills

You can also know whether the web components are successfully loaded WebComponentsReady

1.3 About style conflicts

Regarding styles, the styles in the above example are globally quoted and do not solve the problem of style conflicts. If you want to Web Components and worry about style conflicts between components, you can use Shadow DOM to solve this problem. Similar to scoped processing in defined components in vue

Shadow DOM: Also known as shadow DOM, it can attach a hidden, independent DOM to an element. As shown in the following figure, the official introduction of MDN

image.png

Then how to develop a component hanging on #shadow-root based on web component?

image.png

We can see that by comparing the above figure with the example in the previous section, attachShadow is used. What is it?

Official introduction: Attach a shadow root to any element through attachShadow. It accepts a configuration object as a parameter, which has an attribute of mode When the mode is true, it means that the Shadow DOM can be obtained through the JavaScript method in the page

🌲 Extended reading:

1.4 Pay attention to details

Ale classmate: Shujun, can I use custom components developed by Web Component in vue?

Yes, but one thing to note is that the Vue component development is very similar to custom elements. If we don’t do some "means" processing, Vue will treat your components developed based on Web Component as components under its own framework, so We need to configure ignoredElements , the following figure is an example of the vue official website

image.png

If you want to know more about the component development of Web Component, you can take a look at the following open source component library

2 Mrcio-app

I accidentally walked around, get back to business, talk about today’s protagonist: micro-app

Children's shoes who have used qiankun know that we need to integrate a micro application on the base without the following three elements:

  • Register sub-applications on the base
  • Need to define the life cycle function in the sub-application
  • Modify the webpack packaging method of micro-applications

Although the cost of transformation is not particularly high, can it minimize the intrusiveness of the source code?

Mrcio-app takes a minimalist route. As long as you modify a bit of code, you can realize the integration of micro applications. It claims to be the lowest cost solution for accessing micro front-ends on the market. How does it do it?

2.1 Principle

In essence, micro-app is a micro-front-end architecture WebComponent + HTML Entry implementation

image.png

Official introduction: monitor the element to be rendered through the life cycle function connectedCallback micro-app , load the html of the sub-application and convert it to the DOM structure, recursively query all static resources such as js and css and load, set element isolation, and intercept all dynamically created Script, link and other tags, extract the content of the tag. Put the loaded js into the sandbox after processing by the plug-in system, isolate the CSS resources, and finally put the formatted elements into micro-app , and finally micro-app element into a micro-front-end sub-application. During the rendering process, the life cycle functions bound by the developer will be executed for further operations.
  • About HTML Entry: I believe children who have used qiankun should be familiar with it. It is to load the entry file of the micro application. On the one hand, it fetches the static resource js, CSS and other files of the micro application. On the other hand, it renders the dom of the micro application.
  • class WebComponent: We learned two features in the previous section of learning web Component: CustomElement and ShadowDom . The former allows us to create custom labels, and the latter allows us to create shadow DOMs that support isolation styles and element isolation. is class WebComponent 1610a7340acac2 mentioned for the first time? Essentially, by using CustomElement combined with a custom ShadowDom to achieve the basically consistent function of WebComponent

In other words: allows micro-applications under the micro-front end to achieve true componentization

2.2 Nice mechanism

I think the micro-app has these mechanisms very well:

  • There is no need to pre-define life cycle functions in each micro-application like qiankun, such as: created , mounted etc., but take a different approach. After you integrate in the base, you can directly define it on the base or perform global monitoring. As follows

image.png

In the attribute configuration in the above figure, name is the name configuration of the micro-application, url is the address configuration of the sub-application page, and the others are the definitions of various life cycle functions.

  • Resource address automatic completion: When we load the micro-application on the base, when the micro-application involves the loading of pictures or other resources, if the access path is a relative address, we will find that the static resource will be completed with the domain name address where the base application is located. Caused resource loading error. The micro-app supports the completion of the relative address of the static resource of the sub-application to the absolute address, which solves the above-mentioned problems.

image.png

2.3 Practice

2.3.1 Getting started with the demo

Getting started is also very simple. Take the vue2 application as an example. For details, refer to the github document . Do not repeat statements here

Through the official online demonstration of the vue micro-application Demo, let's take a look at the effect of the integration

image.png

In the console, we can see that after loading the micro-app "vue2" on the base, after the custom label micro-app rendered, it is a complete sub-application Dom, which is a bit similar to the iframe, and then the CSS style of the sub-application has one more The prefix micro-app[name=vue2] . This is to use the name attribute of the label to add a prefix to each style, confine the style influence of the sub-application to the current label area, and avoid style conflicts between various micro-applications. This is the default isolation mechanism of micro-app

Ale classmate: Shujiang, how did he achieve this elemental isolation?

Listen to my explanation, see the next section of source code analysis

2.3.2 The process of rendering micro applications

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

image.png

  • Fetch sub-application HTMl: Get html, then convert it to dom structure and process each sub-element recursively, and do the corresponding processing for different elements source link

The purpose is to extract the link and script of the micro application and bind the style scope. Finally, the core source code of hanging the style of the micro application in micro-app-head
image.png

Through the reading of the source code, when we app.scopecss defined in the initialization of the micro application (enabled by default), scopedCSS will be called to process the dom
, In order to realize the css scope of the binding micro application, let us look at the realization of this method source link

I see in the source code that scoped_css is mainly cssRule to distinguish between several types of 0610a7340b4e93

Ah Heng: Tree sauce, what is Css Rule?

This is a historical concept, CSSRule represents a CSS rule. And a CSS style sheet contains a set of representation rules CSSRule objects. CSSRule has several different rule types. You can distinguish between the following regular cssRules in the micro-app

  • CSSRule.STYLE_RULE: General style rules
  • CSSRule.MEDIA_RULE: CSS @media media attribute query rule
  • CSSRule.SUPPORTS_RULE: CSS @support can define different style rules according to the browser's support for CSS features

image.png

Finally, the successfully converted style content will be appended to the micro-app-head

Ah Heng: Shujiang, did you say that the micro-app isolation element supports shadowDom?

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

Here is a cut version: About mircro-app by Web Component + shadowDOM custom application initialization for the child, the specific source code that you can read the source code framework on micro_app_element defined source link
carbon (8).png

Essentially, after opening shadowDom, the <micro-app> tag can be regarded as a WebComponent in the real sense of realization

3 Write to the end

Regarding the implementation mechanism of JS sandbox and data communication, we will share with children's shoes later

Hello, I am 🌲 tree sauce, please have a drink🍵 Remember Sanlian~

1. After reading, remember to like it, there is 👍 motivated

2. Follow those interesting things on the front end of the official account, and chat with you about the interesting things on the front end

3. The article is included in Github frontendThings, thanks to Star✨


树酱
457 声望953 粉丝

95年程序猿,搞前端,爱音乐,唱跳rap工程🌲