Micro Frontend

[toc]

1. What Is MFE(Micro Frontend)

When I first heard the concept of Micro Frontend, it made me feel it's a Buzzword, like Microservices.But as the pace of usage of that, I knew that's a powerful architecture in our daily development

The term Micro Frontends first came up in ThoughtWorks Technology Radar at the end of 2016.

The Micro Frontends official website defines the concept of micro frontends:

Techniques, strategies and recipes for building a modern web app with multiple teams that can ship features independently.

translate to Chinese:

構(gòu)建一個現(xiàn)代web應(yīng)用所需的技術(shù)弓熏、策略和方法,具備多個團(tuán)隊獨立開發(fā)糠睡、部署的特性

translate to human language:

We can learn that the concept of micro frontends is extended from the concept of microservices . It abandons the large-scale monolithic approach and decomposes the front-end as a whole into small and simple blocks. These blocks can be independently developed, tested and deployed , while still Aggregate as a product to appear in front of customers. It can be understood that micro-frontend is an architectural style that aggregates multiple small front-end applications that can be delivered independently into a whole.

A few points worth noting:

  • Micro-frontend is not a specific technology , but integrates technologies, strategies and methods, and may be displayed in the form of scaffolding, auxiliary plug-ins and specification constraints , which is a macro-level architecture . There are currently a variety of solutions for this architecture , all of which have advantages and disadvantages, but as long as the current business scenario is applicable, it is a good solution.
  • Micro frontends are not constrained by technology stacks . The design of each micro-front-end solution is based on actual needs. If multiple teams use the react technology stack uniformly, there may be no requirements for the cross-technology stack use of the micro-frontend solution; if multiple teams use the react and vue technology stacks at the same time, the cross-technology stack requirements for the micro-frontend may be relatively high

2. From Monolithic Frontend to Micro Frontend

2.1 Monolithic Frontend Structure

As you can see, from the traditional Monolith structure to Microserve structure. Each Microservices in the backend operates independently of each other, each team can have its own deployment and development technology, communication can be achieved through various API interfaces, and various services can be connected to the frontend only by HTTP request.
Under such a structure, the frontend team's code still coexists in a Monolithic structure. When the website functions become more complex and the team grows stronger, the entire frontend structure will become more and more difficult to maintain, not to mention the advanced technology With each passing day, it is easy to generate legacy code, and if you want to update it, it will be troublesome.

2.2 Micro Frontend Structure

As someone slowly realized this kind of problem, the idea of Micro Frontends was put forward:


It is not difficult to find from the figure that Frontend's modules are divided into various teams, each team independently manages its own front-end and back-end services, has its own deployment environment and tech stack, low coupling between teams, and high cohesion among teams.
In addition, the front-end modules produced by each team must be able to be effectively "collaged" in the same SPA page, so that the user experience of the product is consistent with the original SPA.

2.3 The core idea of Micro Frontend

  • Be Technology Agnostic : Each team can use its own technical structure to develop front-end modules, without interfering with other teams and without cost coordination.
  • Isolate Team Code : Even if teams use the same technical framework, they should not share variables or state with each other. They should communicate with each other through a public API.
  • Establish Team Prefixes : Use Prefix to avoid conflicts between CSS, Browser API, Web Events, Cookies or Local Storage.
  • Favor Native Browser Features over Custom APIs : The complexity of integrating Micro Frontends is actually very high. When communication between each module is required, it is better to use Browser Native API as much as possible; if you really need additional communication methods (pub/ sub system), keep it as simple as possible.
  • Build a Resilient Site : Enhance the stability of the website through SSI or PWA, and also have a usable presentation even when JS cannot be executed.

3. Pain points to implement Micro Frontend(how to)

3.1 Isolation

3.1.1 JS Isolation

Each Micro frontend has its own variables and functions, but when they are embed into portal, these variables and functions might conflict with portal. So we need a JS sandbox with individual scope to isolate each micro frontend. There are 2 classical approches to resolve this:

  active() {
    if (this.sandboxRunning) {
      return;
    }


    this.windowSnapshot = {} as Window;
    // iter will traverse target object, and then call the callback
    // recording current window snapshot
    iter(window, prop => {
      this.windowSnapshot[prop] = window[prop];
    });

    Object.keys(this.modifyPropsMap).forEach((p: any) => {
      window[p] = this.modifyPropsMap[p];
    });

    this.sandboxRunning = true;
  }

  inactive() {
    this.modifyPropsMap = {};

    iter(window, prop => {
      if (window[prop] !== this.windowSnapshot[prop]) {
        // recover the window
        this.modifyPropsMap[prop] = window[prop];
        window[prop] = this.windowSnapshot[prop];
      }
    });

    this.sandboxRunning = false;
  }

3.1.2 CSS Isolation

Same as JS isolation, class names of ids of css in each micro frontend may be conflict.

  • BEM(prefix)
  • css in js
  • shadow dom

3.2 Low Coupling(how to load common dependencies)

3.3 Version Control

3.4 Communication

3.5 Hijack Route

3.6 etc...

4. Workaround of Micro frontend

4.1 iframe

In the module of the Team product, the other two modules can be loaded by embedding the iframe. Since the iframe has the characteristic of isolating the running environment, the modules of each team will not interfere with each other. Under the domain, we can use window.postMessage.

<body> 
    <!-- in Team Product --> 
    <iframe width="100%" height="200" src="https://microfrontends-checkout.com/"></iframe> 
    <iframe width="100%" height="200" src="https://microfrontends-inspire.com/"></iframe> 
</body>

Disadvantages:

There are many disadvantages of using iframe.
For example: because the application modules are separated, the shared dependent modules cannot be taken out, resulting in the page may be loaded at the same time. code; in addition, the presentation of the UI will become difficult to control, and if it also contains functions such as forms, it will be even more troublesome.

And iframe only resolve the isolation issue, if we do create a micro frontend, we might also need to pay more effort.

4.2 Web component

The same as iframe, web component is born with the js and css isolation, but it can not be compatible with all browsers. Moreover, when facing high complex componet or system, I think web component cannot handle this easily.

4.3 Single-SPA/Qiankun

Regarding single-SPA, it's only a scheduling of child application lifecycle. It only do 2 things:

  • implement a life cycle, loading child application in load life cycle, and then hand over the control to child application, he doesn't care about the life cycle or statement of child application.
  • monitoring the change of the url address. With the url change, some child applicaitons will be active, then go through the while life.

single-SPA hopes main application would be very very simple and lite, only need a index.html and a main.js is enough. Even webpack it doesn't require

5. Module Federation

Multiple separate builds should form a single application. These separate builds should not have dependencies between each other, so they can be developed and deployed individually. This is often known as Micro-Frontends, but is not limited to that.

// todo pic MF的圖 host remote

const HtmlWebpackPlugin = require("html-webpack-plugin"); 
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); 
module.exports = { 
// 其他webpack配置... 
    plugins: [ 
        new ModuleFederationPlugin({ 
            name: 'empBase', 
            library: { type: 'var', name: 'empBase' }, 
            filename: 'emp.js', 
            remotes: { 
                app_two: "app_two_remote", 
                app_three: "app_three_remote" 
            }, 
            exposes: { 
                './Component1': 'src/components/Component1', 
                './Component2': 'src/components/Component2', 
            }, 
            shared: ["react", "react-dom","react-router-dom"] 
        }) 
    ] 
}
字段名 類型 含義
name string 必傳值挽鞠,即輸出的模塊名,被遠(yuǎn)程引用時路徑為${name}/${expose}
library object 聲明全局變量的方式,name為umd的name
filename string 構(gòu)建輸出的文件名
remotes object 遠(yuǎn)程引用的應(yīng)用名及其別名的映射信认,使用時以key值作為name
exposes object 被遠(yuǎn)程引用時可暴露的資源路徑及其別名
shared object 與其他應(yīng)用之間可以共享的第三方依賴材义,使你的代碼中不用重復(fù)加載同一份依賴
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市嫁赏,隨后出現(xiàn)的幾起案子其掂,更是在濱河造成了極大的恐慌,老刑警劉巖潦蝇,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件款熬,死亡現(xiàn)場離奇詭異,居然都是意外死亡攘乒,警方通過查閱死者的電腦和手機(jī)贤牛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來则酝,“玉大人殉簸,你說我怎么就攤上這事」炼铮” “怎么了喂链?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長妥泉。 經(jīng)常有香客問我椭微,道長,這世上最難降的妖魔是什么盲链? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任蝇率,我火速辦了婚禮,結(jié)果婚禮上刽沾,老公的妹妹穿的比我還像新娘本慕。我一直安慰自己,他們只是感情好侧漓,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布锅尘。 她就那樣靜靜地躺著,像睡著了一般布蔗。 火紅的嫁衣襯著肌膚如雪藤违。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天纵揍,我揣著相機(jī)與錄音顿乒,去河邊找鬼。 笑死泽谨,一個胖子當(dāng)著我的面吹牛璧榄,可吹牛的內(nèi)容都是我干的特漩。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼骨杂,長吁一口氣:“原來是場噩夢啊……” “哼涂身!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起搓蚪,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤蛤售,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后陕凹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體悍抑,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年杜耙,在試婚紗的時候發(fā)現(xiàn)自己被綠了搜骡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡佑女,死狀恐怖记靡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情团驱,我是刑警寧澤摸吠,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站嚎花,受9級特大地震影響寸痢,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜紊选,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一啼止、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧兵罢,春花似錦献烦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至此蜈,卻和暖如春即横,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背舶替。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工令境, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人顾瞪。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓舔庶,卻偏偏與公主長得像,于是被迫代替她去往敵國和親陈醒。 傳聞我的和親對象是個殘疾皇子惕橙,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容