Webpack 5 模块联邦

实现多个独立构建之间共享模块和代码

问题

什么是 Webpack 5 的模块联邦(Module Federation)?

解答

模块联邦是 Webpack 5 引入的新特性,允许多个独立的 Webpack 构建之间共享模块和代码。它基于远程容器特性,可以将应用程序的某些模块打包为独立的、可远程加载的 bundle,并在运行时动态加载。

工作原理

一个应用程序可以将模块暴露给其他应用程序使用,同时也可以消费其他应用程序暴露的模块。这样可以避免重复打包相同的模块或库,提高应用程序的性能。

配置示例

// app1 的 webpack.config.js - 暴露模块
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'app1',
      filename: 'remoteEntry.js',
      exposes: {
        './Button': './src/Button',
        './utils': './src/utils'
      },
      shared: ['react', 'react-dom']
    })
  ]
};
// app2 的 webpack.config.js - 消费模块
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'app2',
      remotes: {
        app1: 'app1@http://localhost:3001/remoteEntry.js'
      },
      shared: ['react', 'react-dom']
    })
  ]
};
// app2 中使用 app1 的模块
import Button from 'app1/Button';
import { formatDate } from 'app1/utils';

function App() {
  return <Button onClick={() => console.log(formatDate(new Date()))}>Click</Button>;
}

关键点

  • 减少重复代码:多个应用程序共享相同的模块和依赖,避免重复打包
  • 微前端架构:支持将大型应用拆分为多个独立的子应用,降低复杂度
  • 运行时加载:模块在运行时动态加载,无需在构建时打包所有依赖
  • 版本管理:支持应用程序的独立部署和升级,实现更灵活的版本控制
  • 共享依赖:通过 shared 配置共享公共库(如 React),确保只加载一次