本文介紹了Module Federation的概念、應(yīng)用場景,并結(jié)合具體的代碼示例幫助大家對Module Federation的模塊共享,公共依賴加載有個初步的認(rèn)識,方便后續(xù)更深入的學(xué)習(xí)相關(guān)內(nèi)容,同時也給微前端的探索提供一種新的思路,定會給大家一定的提升和啟發(fā)。
1、什么是Module Federation(MF)?
普遍直譯為『模塊聯(lián)邦』,我們看看官網(wǎng)是怎么說的?
Motivation
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.
多個獨立的構(gòu)建可以形成一個應(yīng)用程序。這些獨立的構(gòu)建不會相互依賴,因此可以單獨開發(fā)和部署它們。
這通常被稱為微前端,但并不僅限于此。
通俗點講,即MF提供了能在當(dāng)前應(yīng)用中遠(yuǎn)程加載其他服務(wù)器上應(yīng)用的能力。對此,可以引出下面兩個概念:
- host:引用了其他應(yīng)用的應(yīng)用
- remote:被其他應(yīng)用所使用的應(yīng)用

它與我們普遍討論的基座應(yīng)用、微應(yīng)用有所不同,它是去中心化的,相互之間是平等的,每個應(yīng)用是單獨部署在各自的服務(wù)器,每個應(yīng)用都可以引用其他應(yīng)用,也能被其他應(yīng)用所引用,即每個應(yīng)用可以充當(dāng)host的角色,亦可以作為remote出現(xiàn)。

2、應(yīng)用場景
- 微前端:通過shared以及exposes可以將多個應(yīng)用引入同一應(yīng)用中進(jìn)行管理。
- 資源復(fù)用,減少編譯體積:可以將多個應(yīng)用都用到的通用組件單獨部署,通過MF的功能在runtime時引入到其他項目中,這樣組件代碼就不會編譯到項目中,同時亦能滿足多個項目同時使用的需求,一舉兩得。
3、如何使用
項目結(jié)構(gòu)如下:
module-home:首頁,在layout展示一個字符串。
module-layout:布局,只包含一個html模板。
module-lib:暴露工具方法,共享lodash庫。

3.1 相關(guān)配置參數(shù)一覽

3.2 各應(yīng)用的配置
// apps/module-lib/webpack.config.js
plugins: [
new ModuleFederationPlugin({
name: 'lib',
filename: 'remoteLib.js',
library: { type: 'var', name: 'lib' },
exposes: {
// 提供工具方法
'./utils': './index.js',
},
shared: ["lodash"]
})
]
// apps/module-home/webpack.config.js
plugins: [
new ModuleFederationPlugin({
name: 'home',
filename: 'remoteHome.js',
library: { type: 'var', name: 'home' },
exposes: {
// 提供掛載方法
'./mount': './index.js',
},
shared: ["lodash"]
})
]
// apps/module-layout/webpack.config.js
plugins: [
new ModuleFederationPlugin({
name: 'main',
filename: 'remoteMain.js',
remotes: {
'lib': 'lib@http://localhost:3001/remoteLib.js',
'home': 'home@http://localhost:3003/remoteHome.js',
},
shared: ['lodash']
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './public/index.html'),
inject: 'body'
})
]
// apps/module-layout/boot.js
import {getUid, setUid} from 'lib/utils' // 使用module-lib中暴露的方法
import {mount} from 'home/mount' // 使用module-home中暴露的掛載方法
import _ from 'lodash';
setUid();
setUid();
console.log(getUid())
console.log(_.get)
mount()
如下圖所示:在layout中展示了home掛載的節(jié)點,控制臺也打印了調(diào)用lib中方法的log,同時lib分享的lodash也生效了(全程只加載了一個lodash)。


3.3 以remoteLib為例簡要分析
// 定義全局變量
var lib;
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "webpack/container/entry/lib":
/*!***********************!*\
!*** container entry ***!
\***********************/
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
eval("var moduleMap = {\n\t\"./utils\": () => {\n\t\treturn __webpack_require__.e(\"index_js\").then(() => (() => ((__webpack_require__(/*! ./index.js */ \"./index.js\")))));\n\t}\n};\nvar get = (module, getScope) => {\n\t__webpack_require__.R = getScope;\n\tgetScope = (\n\t\t__webpack_require__.o(moduleMap, module)\n\t\t\t? moduleMap[module]()\n\t\t\t: Promise.resolve().then(() => {\n\t\t\t\tthrow new Error('Module \"' + module + '\" does not exist in container.');\n\t\t\t})\n\t);\n\t__webpack_require__.R = undefined;\n\treturn getScope;\n};\nvar init = (shareScope, initScope) => {\n\tif (!__webpack_require__.S) return;\n\tvar name = \"default\"\n\tvar oldScope = __webpack_require__.S[name];\n\tif(oldScope && oldScope !== shareScope) throw new Error(\"Container initialization failed as it has already been initialized with a different share scope\");\n\t__webpack_require__.S[name] = shareScope;\n\treturn __webpack_require__.I(name, initScope);\n};\n\n// This exports getters to disallow modifications\n__webpack_require__.d(exports, {\n\tget: () => (get),\n\tinit: () => (init)\n});\n\n//# sourceURL=webpack://module-lib/container_entry?");
/***/ })
1、moduleMap:用來映射expose的模塊
2、get方法:導(dǎo)出給host應(yīng)用,用于獲取remote expose的模塊
3、init方法:導(dǎo)出給host應(yīng)用,用于將remote模塊注入
get方法中調(diào)用了__webpack_require__.e加載chunk
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = (chunkId) => {
/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ __webpack_require__.f[key](chunkId, promises);
/******/ return promises;
/******/ }, []));
/******/ };
__webpack_require__.e調(diào)用__webpack_require__.f
/******/ __webpack_require__.f.consumes = (chunkId, promises) => {
/******/ if(__webpack_require__.o(chunkMapping, chunkId)) {
/******/ chunkMapping[chunkId].forEach((id) => {
// 如果host已經(jīng)有則直接使用,否則去remote安裝
/******/ if(__webpack_require__.o(installedModules, id)) return promises.push(installedModules[id]);
/******/ var onFactory = (factory) => {
/******/ installedModules[id] = 0;
/******/ __webpack_require__.m[id] = (module) => {
/******/ delete __webpack_require__.c[id];
/******/ module.exports = factory();
/******/ }
/******/ };
/******/ var onError = (error) => {
/******/ delete installedModules[id];
/******/ __webpack_require__.m[id] = (module) => {
/******/ delete __webpack_require__.c[id];
/******/ throw error;
/******/ }
/******/ };
/******/ try {
/******/ var promise = moduleToHandlerMapping[id]();
/******/ if(promise.then) {
/******/ promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));
/******/ } else onFactory(promise);
/******/ } catch(e) { onError(e); }
/******/ });
/******/ }
/******/ }
/******/ })();
- host加載自己的bundle main.js,其中使用jsonp加載對應(yīng)remote提供的remoteLib.js;
- 在remote中暴露了全局變量,host將remote注入后可以獲取對應(yīng)模塊,其中的共享模塊使用前會檢查自身有沒有,如果沒有再去加載remote的內(nèi)容。
4、拓展學(xué)習(xí)
可以學(xué)習(xí)開源項目:基于 Webpack 5 Module Federation,優(yōu)雅且實用的微前端解決方案 https://github.com/yuzhanglong/mf-lite。