一、什么是联邦模块(Module Federation)
联邦模块是webpack5提供的一个新特性,它是通过webpack原生提供的 ModuleFederationPlugin 插件来实现的。联邦模块主要是用来解决多个应用之间代码共享的问题,可以让我们的更加优雅的实现跨应用的代码共享
二、联邦模块的使用
1.动态导入远程模块
step1: 消费通过加载远程js文件【http://localhost:3001/remote-entry.js】,获取远程联邦模块暴露的对象window[scope](container)
step2: 初始化共享作用域。用填入host的共享模块;
step3: 通过container.init方法进行初始化作用域对象initScope & 收集依赖到共享作用域对象shareScope
step4: 通过container.get方法加载远程模块

2.静态导入模块
远程组件

本地组件

三、ModuleFederationPlugin
原理源码中 ModuleFederationPlugin 主流程 主要做了三件事:
通过参数是否配置 shared 来判断是否使用共享依赖 SharePlugin 模块。
通过参数是否配置 exposes 来判断是否使用公开 ContainerPlugin 模块。
通过参数是否配置 remotes 来判断是否使用 ContainerReferencePlugin 引用模块。
sharePlugin

ContainerPlugin

__webpack_require__.I(name, initScope)方法
这段代码所做的就是根据配置项将模块生成内部对应的 modules,定义了一个 scope 去存储所有的 module,然后注册了共享模块等操作。全部挂载在__webpack_require__上,这样处理以方便后续 require 的方式引入进来

生成共享模块对象

ContainerReferencePlugin
该插件先将远程模块的引用存入__webpack_modules__里面

使用远程模块的文件,会被webpack5新增的方法_webpack_require__.e导入【src_bootstrap_js】,这个方法包含三块:
1.加载共享模块:__webpack_require__.f.overridables = (chunkId, promises) => {};
2.加载远程联邦模块:__webpack_require__.f.remotes = (chunkId, promises) => {};
3.加载js:__webpack_require__.f.j = (chunkId, promises) => {};
overridables

其中__webpack_require__.Overrides在A的产物冲,用B产物提供的override方法override方法填充的共享模块列表
step1: B产物中定义override方法

step2: A产物中调用override方法进行本地共享模块填充

remotes

四、流程图

网友评论