百度工程师带你了解Module Federation

开发 前端
本文介绍了Module Federation的概念、应用场景,并结合具体的代码示例帮助大家对Module Federation的模块共享,公共依赖加载有个初步的认识,方便后续更深入的学习相关内容,同时也给微前端的探索提供一种新的思路,定会给大家一定的提升和启发。

1、什么是Module Federation(MF)?

普遍直译为『模块联邦』,我们看看官网是怎么说的?

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.

多个独立的构建可以形成一个应用程序。这些独立的构建不会相互依赖,因此可以单独开发和部署它们。

这通常被称为微前端,但并不仅限于此。

通俗点讲,即MF提供了能在当前应用中远程加载其他服务器上应用的能力。对此,可以引出下面两个概念:

  • host:引用了其他应用的应用
  • remote:被其他应用所使用的应用

图片

它与我们普遍讨论的基座应用、微应用有所不同,它是去中心化的,相互之间是平等的,每个应用是单独部署在各自的服务器,每个应用都可以引用其他应用,也能被其他应用所引用,即每个应用可以充当host的角色,亦可以作为remote出现。

图片

2、应用场景

  • 微前端:通过shared以及exposes可以将多个应用引入同一应用中进行管理。
  • 资源复用,减少编译体积:可以将多个应用都用到的通用组件单独部署,通过MF的功能在runtime时引入到其他项目中,这样组件代码就不会编译到项目中,同时亦能满足多个项目同时使用的需求,一举两得。

3、如何使用

项目结构如下:

module-home:首页,在layout展示一个字符串。

module-layout:布局,只包含一个html模板。

module-lib:暴露工具方法,共享lodash库。

图片

3.1 相关配置参数一览

图片

3.2 各应用的配置

// 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挂载的节点,控制台也打印了调用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方法:导出给host应用,用于获取remote expose的模块
3、init方法:导出给host应用,用于将remote模块注入


get方法中调用了__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调用__webpack_require__.f


/******/ __webpack_require__.f.consumes = (chunkId, promises) => {
/******/ if(__webpack_require__.o(chunkMapping, chunkId)) {
/******/ chunkMapping[chunkId].forEach((id) => {
// 如果host已经有则直接使用,否则去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加载对应remote提供的remoteLib.js;
  • 在remote中暴露了全局变量,host将remote注入后可以获取对应模块,其中的共享模块使用前会检查自身有没有,如果没有再去加载remote的内容。

4、拓展学习

可以学习开源项目:基于 Webpack 5 Module Federation,优雅且实用的微前端解决方案 https://github.com/yuzhanglong/mf-lite。

责任编辑:武晓燕 来源: 百度Geek说
相关推荐

2013-07-01 16:36:26

百度云推送免费云推送移动开发

2012-08-24 10:01:56

百度前端工程师

2012-11-25 15:42:47

互联网百度搜索

2023-02-22 14:04:54

2020-03-23 08:34:50

百度工程师判刑

2016-04-15 13:45:48

2010-03-17 10:31:28

网络工程师

2009-12-22 09:27:27

百度招聘工程师

2012-02-01 13:25:47

百度

2013-08-22 17:08:50

2014-07-25 17:12:39

数据库WOT2014MongoDB

2009-09-15 09:49:02

百度招聘

2015-03-16 16:01:40

Web前端前端工程师Web

2012-05-28 22:51:53

百度

2018-09-06 18:37:45

百度云

2016-04-12 11:06:49

百度开放云存储WOT2016

2012-03-21 17:30:21

百度架构师

2020-12-03 06:13:46

iOS

2016-03-25 11:18:23

中华网

2013-06-27 10:23:30

百度云百度开放云
点赞
收藏

51CTO技术栈公众号