跳到主要内容

Module Federation 模块联邦

通过 模块联邦 也可以实现微前端架构

Module Federation 模块联邦 概述

Module Federation 即为模块联邦,是 Webpack 5 中新增的一项功能,可以实现跨应用共享模块。

我们有两个应用:A应用和B应用。
A应用中提供了一个方法:sayHelloFromA
B应用中提供了一个方法:sayHelloFromB
我们想要在A应用中调用B应用提供的方法,B应用调用A应用提供的方法【跨应用调用方法】
我们可以把一个应用当做一个模块,这样我们就可以在一个应用中加载另一个应用了,只要我们可以在一个应用中加载另一个应用我们就可以实现微前端架构

快速开始-demo

需求:通过模块联邦在容器应用中加载微应用

1. 创建应用结构

按照以下目录结构构建好三个微应用的应用结构,package.jsonpackage-lock.json 文件初始体验可以直接 copy 完成demo 中的文件 html 中初始化好各自的内容 安装各自的依赖

products
├── package-lock.json
├── package.json
├── public // 静态资源文件
│ └── index.html
├── src // 源码
│ └── index.js
└── webpack.config.js

2. 应用初始化

  1. 在入口 JavaScript 文件中加入产品列表

    // faker 可以用来随机生成数据
    import faker from 'faker'

    let products = '';

    for (let i = 1; i <= 5; i++) {
    products += `<div>${faker.commerce.productName()}</div>`
    }

    document.querySelector("#products").innerHTML = products
  2. 在入口 html 文件中加入盒子

    <div id="products"></div>
  3. webpack 配置

    const HtmlWebpackPlugin = require("html-webpack-plugin")

    module.exports = {
    mode: "development",
    devServer: {
    port: 8081
    },
    plugins: [
    new HtmlWebpackPlugin({
    template: "./public/index.html"
    })
    ]
    }
  4. 添加应用启动命令

    "scripts": {
    "start": "webpack serve"
    },
  5. 通过 copy 的方式创建 container 和 cart

3. Module Federation

通过配置模块联邦实现在容器应用中加载产品列表微应用。

  1. 在产品列表微应用中将自身作为模块进行导出

    // webpack.config.js
    // 导入模块联邦插件
    const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
    // 将 products 自身当做模块暴露出去
    new ModuleFederationPlugin({
    // 模块文件名称, 其他应用引入当前模块时需要加载的文件的名字
    filename: "remoteEntry.js",
    // 模块名称, 具有唯一性, 相当于 single-spa 中的组织名称
    name: "products",
    // 当前模块具体导出的内容
    exposes: { "./index": "./src/index" },
    });
    // 在容器应用中要如何引入产品列表应用模块?
    // 1. 在容器应用中加载产品列表应用的模块文件
    // 2. 在容器应用中通过 import 关键字从模块文件中导入产品列表应用模块
  2. 在容器应用的中导入产品列表微应用

    // webpack.config.js
    // 导入模块联邦插件
    const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
    new ModuleFederationPlugin({
    name: "container",
    // 配置导入模块映射
    remotes: {
    // 字符串 "products" 和被导入模块的 name 属性值对应
    // 属性 products 是映射别名, 是在当前应用中导入该模块时使用的名字
    products: "products@http://localhost:8081/remoteEntry.js",
    },
    });
    // src/index.js 
    // 因为是从另一个应用中加载模块, 要发送请求所以使用异步加载方式
    import("products/index").then(products => console.log(products))

    通过上面这种方式加载在写法上多了一层回调函数, 不是很方便, 所以一般都会在 src 文件夹中建立bootstrap.js,在形式上将写法变为同步

    // src/index.js 
    import('./bootstrap.js')

    // src/bootstrap.js
    import "products/index"
  3. 实现 Cart 微应用加载 注意:cart/index.html 和 products/index.html 仅仅是在开发阶段中各自团队使用的文件,而 container/index.html 是在开发阶段和生产阶段都要使用的文件。

共享模块

实现模块共享

在 Products 和 Cart 中都需要 Faker,当 Container 加载了这两个模块后,Faker 被加载了两次。

// 分别在 Products 和 Cart 的 webpack 配置文件中的模块联邦插件中添加以下代码 
// 如果遇到版本不一致的问题,强制使用高版本
{
shared: ["faker"]
}
// 重新启动 Container、Products、Cart

注意:共享模块需要异步加载,在 Products 和 Cart 中需要添加 bootstrap.js

共享模块版本冲突解决

Cart 中如果使用 4.1.0 版本的 faker,Products 中使用 5.2.0 版本的 faker,通过查看网络控制面板可以发现 faker 又会被加载了两次,模块共享失败。 解决办法是分别在 Products 和 Cart 中的 webpack 配置中加入如下代码

shared: {
faker: {
singleton: true
}
}

但同时会在原本使用低版本的共享模块应用的控制台中给予警告提示。

开放子应用挂载接口

在容器应用导入微应用后,应该有权限决定微应用的挂载位置,而不是微应用在代码运行时直接进行挂 载。所以每个微应用都应该导出一个挂载方法供容器应用调用。

Products/bootstrap.js

// faker 可以用来随机生成数据
import faker from "faker";

function mount(el) {
let products = "";

for (let i = 1; i <= 5; i++) {
products += `<div>${faker.commerce.productName()}</div>`;
}

el.innerHTML = products;
}

// 此处代码是 products 应用在本地开发环境下执行的
if (process.env.NODE_ENV === "development") {
const el = document.querySelector("#dev-products");
// 当容器应用在本地开发环境下执行时也可以进入到以上这个判断, 容器应用在执行当前代码时肯定是获 取不到 dev-products 元素的, 所以此处还需要对 el 进行判断.
if (el) mount(el);
}
export { mount };

Products/webpack.config.js

exposes: {
// ./src/index => ./src/bootstrap 为什么 ?
// mount 方法是在 bootstrap.js 文件中导出的, 所以此处要导出 bootstrap
// 此处的导出是给容器应用使用的, 和当前应用的执行没有关系, 当前应用在执行时依然先执行 index
"./Index": "./src/bootstrap",
},

Container/bootstrap.js

import { mount as mountProducts } from "products/Index";
mountProducts(document.querySelector("dev-products"));

基于模块联邦的微前端实现方案

应用案例概述

当前案例中包含三个微应用,分别为 Marketing、Authentication 和 Dashboard

  1. Marketing: 营销微应用,包含首页组件和价格组件
  2. Authentication:身份验证微应用,包含登录组件
  3. Dashboard:仪表盘微应用,包含仪表盘组件

容器应用、营销应用、身份验证应用使用 React 框架,仪表盘应用使用 Vue 框架。

Marketing

应用初始化

1. 创建应用结构

├── public
│ └── index.html
├── src
│ ├── bootstrap.js
│ └── index.js
├── package-lock.json
├── package.json
└── webpack.config.js

index.html

<title>Marketing</title>
<div id="dev-marketing"></div>

index.js

import("./bootstrap")

bootstrap.js

console.log('测试用例')

2. 配置 webpack

const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
mode: "development",
devServer: {
port: 8081,
// 当使用 HTML5 History API 时, 所有的 404 请求都会响应 index.html 文件
historyApiFallback: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-react", "@babel/preset-env"],
// 1. 避免 babel 转义语法后 helper 函数重复
// 2. 避免 babel polyfill 将 API 添加到全局
plugins: ["@babel/plugin-transform-runtime"]
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html"
})
]
}

3. 添加启动命令

"scripts": {
"start": "webpack serve"
}

创建挂载方法

bootstrap.js

import React from "react"
import ReactDOM from "react-dom"

function mount(el) {
ReactDOM.render(<div>test</div>, el)
}

if (process.env.NODE_ENV === "development") {
const el = document.querySelector("#dev-marketing")
if (el) mount(el)
}

export { mount }

创建路由

  1. 在 src 文件夹中创建 components 文件夹用于放置页面组件
  2. 在 src 文件夹中创建 App 组件,用于编写路由

App.js

import React from "react"
import { BrowserRouter, Route, Switch } from "react-router-dom"
import Landing from "./components/Landing"
import Pricing from "./components/Pricing"

function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/pricing">
<Pricing />
</Route>
<Route path="/">
<Landing />
</Route>
</Switch>
</BrowserRouter>
)
}

export default App
// bootstrap.js
import App from "./App"
function mount(el) {
ReactDOM.render(<App />, el)
}

Container

应用初始化

1. 创建应用结构 (基于 Marketing 应用进行拷贝修改)

├── public
│ └── index.html
├── src
│ ├── bootstrap.js
│ └── index.js
├── package-lock.json
├── package.json
└── webpack.config.js

2. 修改 index.html

<title>Container</title>
<div id="root"></div>

3. 修改 App.js

import React from "react"
export default function App() {
return <div>Container works</div>
}

4. 修改 bootstrap.js

if (process.env.NODE_ENV === "development") { 
const el = document.querySelector("#root")
if (el) mount(el)
}

5. 修改 webpack.config.js

module.exports = { 
devServer: {
port: 8080
}
}

加载 Marketing

1. Marketing 应用配置 ModuleFederation

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin")
new ModuleFederationPlugin({
name: "marketing",
filename: "remoteEntry.js",
exposes: {
"./MarketingApp": "./src/bootstrap"
}
})

2. Container 应用配置 ModuleFederation

const ModuleFederationPlugin =
require("webpack/lib/container/ModuleFederationPlugin")
new ModuleFederationPlugin({
name: "container",
remotes: {
marketing: "marketing@http://localhost:8081/remoteEntry.js"
}
})

3. 在 Container 应用中新建 MarketingApp 组件,用于挂载 Marketing 应用

// Container/components/MarketingApp.js
import React, { useRef, useEffect } from "react"
import { mount } from "marketing/MarketingApp"
export default function MarketingApp() {
const ref = useRef()
useEffect(() => {
mount(ref.current)
}, [])
return <div ref={ref}></div>
}

4. 在 Container 应用中的 App 组件中渲染 Marketing 应用的

// Container/App.js
import React from "react"
import MarketingApp from "./components/MarketingApp"
export default function App() {
return <MarketingApp />
}

共享库设置

在 Container 应用和 Marketing 应用中都使用了大量的相同的代码库,如果不做共享处理,则应用中相同的共享库会被加载两次。

"dependencies": { 
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0"
}

在 Container 应用和 Marketing 应用的 webpack 配置文件中加入以下代码

const packageJson = require("./package.json")
new ModuleFederationPlugin({
shared: packageJson.dependencies
})

路由配置

概述

容器应用路由用于匹配微应用,微应用路由用于匹配组件。

容器应用使用 BrowserHistory 路由,微应用使用 MemoryHistory 路由。

  1. 为防止容器应用和微应用同时操作 url 而产生冲突,在微前端架构中,只允许容器应用更新 url, 微应用不允许更新 url,MemoryHistory 是基于内存的路由,不会改变浏览器地址栏中的 url。

  2. 如果不同的应用程序需要传达有关路由的相关信息,应该尽可能的使用通过的方式, memoryHistory 在 React 和 Vue 中都有提供。

更新现有路由配置

1. 容器应用的路由配置

// Container/App.js
import { Router, Route, Switch } from "react-router-dom"
import { createBrowserHistory } from "history"
const history = createBrowserHistory()
export default function App() {
return (
<Router history={history}>
<Switch>
<Route path="/">
<MarketingApp />
</Route>
</Switch>
</Router>
) }

2. Marketing 应用的路由配置

// Marketing/bootstrap.js
import { createMemoryHistory } from "history"
function mount(el) {
const history = createMemoryHistory()
ReactDOM.render(<App history={history} />, el)
}
// Marketing/app.js
import { Router, Route, Switch } from "react-router-dom"
export default function App({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/pricing" component={Pricing} />
<Route path="/" component={Landing} />
</Switch>
</Router>
) }

3. 添加头部组件

import Header from "./components/Header"
export default function App() {
return <Header />
}

微应用和容器应用路由沟通

  1. 微应用路由变化时 url 地址没有被同步到浏览器的地址栏中,路由变化也没有被同步到浏览器的历史记录中。 当微应用路由发生变化时通知容器应用更新路由信息 (容器应用向微应用传递方法)。

    // Container/components/MarketingApp.js
    import { useHistory } from "react-router-dom"
    const history = useHistory()
    mount(ref.current, {
    onNavigate({ pathname: nextPathname }) {
    const { pathname } = history.location
    if (pathname !== nextPathname) {
    history.push(nextPathname)
    }
    }
    })
    // Marketing/bootstrap.js
    function mount(el, { onNavigate }) {
    if (onNavigate) history.listen(onNavigate)
    }
  2. 容器应用路由发生变化时只能匹配到微应用,微应用路由并不会响应容器应用路由的变化。 当容器应用路由发生变化时需要通知微应用路由进行响应 (微应用向容器应用传递方法)

    // Marketing/bootstrap.js
    function mount(el, { onNavigate }) {
    return {
    onParentNavigate({ pathname: nextPathname }) {
    const pathname = history.location.pathname;
    if (nextPathname !== pathname) {
    history.push(nextPathname);
    }
    },
    };
    }
    // Container/components/MarketingApp.js
    const { onParentNavigate } = mount(...)
    if (onParentNavigate) history.listen(onParentNavigate);

Marketing 应用本地路由设置

目前 Marketing 应用本地开发环境是报错的,原因是本地开发环境在调用 mount 方法时没有传递第二个参数,默认值就是 undefined, mount 方法内部试图从 undefined 中解构 onNavigate,所以就报错了。解决办法是在本地开发环境调用mount 方法时传递一个空对象。

if (process.env.NODE_ENV === "development") {
// ...
if (el)
mount(el, {});
}

如果当前为本地开发环境,路由依然使用 BrowserHistory,所以在调用 mount 方法时传递 defaultHistory 以做区分。

// Marketing/bootstrap.js
if (process.env.NODE_ENV === "development") {
// ...
if (el)
mount(el, {
defaultHistory: createBrowserHistory(),
});
}

在 mount 方法内部判断 defaultHistory 是否存在,如果存在就用 defaultHistory,否则就用MemoryHistory。

// Marketing/bootstrap.js
function mount(el, { onNavigate, defaultHistory }) {
const history = defaultHistory || createMemoryHistory()
}

Authentication

应用初始化

1. 拷贝 src 文件夹并做如下修改

// bootstrap.js
if (process.env.NODE_ENV === "development") {
const el = document.querySelector("#dev-auth")
}
 
// App.js
import React from "react"
import { Router, Route, Switch } from "react-router-dom"
export default function App({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/auth/signin" component={Signin}></Route>
</Switch>
</Router>
)
}

2. 拷贝 public 文件夹,并修改 index.html

<div id="dev-auth"></div>

3. 拷贝 webpack.config.js 文件并进行修改

module.exports = { 
devServer: {
port: 8082
},
plugins: [
new ModuleFederationPlugin({
name: "auth",
exposes: {
"./AuthApp": "./src/bootstrap"
}
})
]
}

4. 添加应用启动命令

// package.json
"scripts": {
"start": "webpack serve"
}

5. 修改 publicPath 更正文件的访问路径

// webpack.config.js
module.exports = {
output: {
publicPath: "http://localhost:8082/"
}
}

6. 更正其他微应用的 publicPath

// Container/webpack.config.js
output: {
publicPath: "http://localhost:8080/"
}
// Marketing/webpack.config.js
output: {
publicPath: "http://localhost:8081/"
}

Container 应用加载 AuthApp

1. 在 Container 应用的 webpack 中配置添加 AuthApp 的远端地址

// Container/webpack.config.js
remotes: {
auth: "auth@http://localhost:8082/remoteEntry.js"
}

2. 在 Container 应用的 components 文件夹中新建 AuthApp.js,并拷贝 MarketingApp.js 中的内容进行修改

import { mount } from "auth/AuthApp"
export default function AuthApp() {}

3. 在 Container 应用的 App.js 文件中配置路由

<Router history={history}>
<Header />
<Switch>
<Route path='/auth/signin'>
<AuthApp setStatus={setStatus} />
</Route>
<Route path='/'>
<MarketingApp />
</Route>
</Switch>
</Router>

4. 解决登录页面点击两次才显示的 Bug

当点击登录按钮时,容器应用的路由地址是 /auth/signin,加载 AuthApp,但是 AuthApp 在首次加载时默认访问的是 /,因为在使用 createMemoryHistory 创建路由时没有传递初始参数,当再次点击登录按钮时,容器应用通知微应用路由发生了变化,微应用同步路由变化,所以最终看到了登录页面。

解决问题的核心点在于微应用在初始创建路由对象时应该接收一个默认参数,默认参数就来自于容 器应用。

// auth/bootstrap.js
function mount(el, { onNavigate, defaultHistory, initialPath }) {
createMemoryHistory({
initialEntries: [initialPath]
})
}
// container/src/components/AuthApp.js
mount(ref.current, {
initialPath: history.location.pathname
})

5. 按照上述方法修正 MarketingApp

懒加载微应用

目前所有的微应用都会在用户初始访问时被加载,这样会导致加载时间过长,解决办法就是懒加载微应用。

import React, { lazy, Suspense, useState, useEffect } from "react";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import Progress from "./components/Progress";

const MarketingApp = lazy(() => import("./components/MarketingApp"));
const AuthApp = lazy(() => import("./components/AuthApp"));

function App() {
return (
<Router history={history}>
<Suspense fallback={<Progress />}>
<Switch>
<Route path='/auth/signin'>
<AuthApp setStatus={setStatus} />
</Route>
<Route path='/'>
<MarketingApp />
</Route>
</Switch>
</Suspense>
</Router>
);
}

export default App;

登录状态

设置登录状态

由于每个微应用都有可能用到登录状态以及设置登录状态的方法,所以登录状态和设置登录状态的方法需要放置在容器应用中。

// Container/App.js
export default function App() {
// 存储登录状态
const [status, setStatus] = useState(false)
return <AuthApp setStatus={setStatus} />
}
// Container/AuthApp.js
export default function AuthApp({ setStatus }) {
useEffect(() => {
mount(ref.current, { setStatus })
}, [])
}
// Auth/bootstrap.js
function mount(el, { setStatus }) {
ReactDOM.render(<App setStatus={setStatus} />, el)
}
// Auth/App.js
export default function App({ setStatus }) {
return <Signin setStatus={setStatus} />
}
// Auth/Signin.js
export default function SignIn({ setStatus }) {
return <Button onClick={() => setStatus(true)}>登录</Button>
}

登录状态应用

根据登录状态更改头部组件右侧的按钮文字,如果是未登录状态显示登录,如果是登录状态,显示退出。点击退出按钮取消登录状态。 如果登录状态为真,跳转到 Dashboard 应用。

// Container/App.js
export default function App() {
const [status, setStatus] = useState(false)
// 如果登录状态为真,跳转到 Dashboard 应用
useEffect(() => {
if (status) history.push("/dashboard")
}, [status])
return (
<Router history={history}>
{/* 将登录状态和设置登录状态的方法传递到头部组件 */}
<Header status={status} setStatus={setStatus} />
</Router>
)
}
// Container/Header.js
export default function Header({ status, setStatus }) {
// 当点击按钮时取消登录状态
const onClick = () => {
if (status && setStatus) setStatus(false)
}
return <Button
to={status ? "/" : "/auth/signin"}
onClick={onClick}
>{status ? "退出" : "登录"}</Button>
}

Dashboard

初始化

1. 新建 public 文件夹并拷贝 index.html 文件

<div id="dev-dashboard"></div>

2. 新建 src 文件夹并拷贝 index.js 和 bootstrap.js

// bootstrap.js
import { createApp } from "vue"
import Dashboard from "./components/Dashboard.vue"
function mount(el) {
const app = createApp(Dashboard)
app.mount(el)
}
if (process.env.NODE_ENV === "development") {
const el = document.querySelector("#dev-dashboard")
if (el) mount(el)
}
export { mount }

3. 拷贝 webpack.config.js 文件并做如下修改

const HtmlWebpackPlugin = require("html-webpack-plugin")
const { VueLoaderPlugin } = require("vue-loader")
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin")
const packageJson = require("./package.json")

module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
publicPath: "http://localhost:8083/",
filename: "[name].[contentHash].js"
},
resolve: {
extensions: [".js", ".vue"]
},
devServer: {
port: 8083,
historyApiFallback: true,
headers: {
"Access-Control-Allow-Origin": "*"
}
},
module: {
rules: [
{
test: /\.(png|jpe?g|gif|woff|svg|eot|ttf)$/i,
use: [
{
loader: "file-loader"
}
]
},
{
test: /\.vue$/,
use: "vue-loader"
},
{
test: /\.scss|\.css$/,
use: ["vue-style-loader", "style-loader", "css-loader", "sass-loader"]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
plugins: ["@babel/plugin-transform-runtime"]
}
}
}
]
},
plugins: [
new ModuleFederationPlugin({
name: "dashboard",
filename: "remoteEntry.js",
exposes: {
"./DashboardApp": "./src/bootstrap"
},
shared: packageJson.dependencies
}),
new HtmlWebpackPlugin({
template: "./public/index.html"
}),
new VueLoaderPlugin()
]
}

4. 修改启动命令

"scripts": {
"start": "webpack serve"
}

Container 应用加载 Dashboard

1. Container 配置 ModuleFedaration

// container/webpack.config.js
remotes: {
dashboard: "dashboard@http://localhost:8083/remoteEntry.js"
}

2. 新建 DashboardApp 组件

import React, { useRef, useEffect } from "react"
import { mount } from "dashboard/DashboardApp"
export default function DashboardApp() {
const ref = useRef()
useEffect(() => {
mount(ref.current)
}, [])
return <div ref={ref}></div>
}

3. Container 应用添加路由

const DashboardApp = lazy(() => import("./components/DashboardApp"))
function App () {
return (
<Route path="/dashboard">
<DashboardApp />
</Route>
) }

Dashboard 路由保护

function App () {
const [status, setStatus] = useState(false)
useEffect(() => {
if (status) history.push("/dashboard")
}, [status])
return (
<Router history={history}>
<Route path="/dashboard">
{!status && <Redirect to="/" />}
<DashboardApp />
</Route>
</Router>
)
}
 // Marketing/Landing.js
<Link to="/dashboard">
<Button variant="contained" color="primary">
Dashboard
</Button>
</Link>