微前端架构落地:Module Federation 实战

微前端架构落地:Module Federation 实战

微前端架构让大型前端应用可以拆分为独立开发、独立部署的子应用。Webpack 5 的 Module Federation 提供了运行时模块共享的能力,是目前最成熟的微前端方案之一。

主机应用配置:

示意图
示意图
// webpack.config.js (主机应用)
const { ModuleFederationPlugin } = require("webpack").container;

module.exports = {
    plugins: [
        new ModuleFederationPlugin({
            name: "host",
            remotes: {
                catalog: "catalog@http://cdn.example.com/catalog/remoteEntry.js",
                cart: "cart@http://cdn.example.com/cart/remoteEntry.js",
            },
            shared: {
                react: { singleton: true, requiredVersion: "^18.0.0" },
                "react-dom": { singleton: true, requiredVersion: "^18.0.0" },
            },
        }),
    ],
};

远程应用配置:

// webpack.config.js (远程应用 - 商品目录)
module.exports = {
    plugins: [
        new ModuleFederationPlugin({
            name: "catalog",
            filename: "remoteEntry.js",
            exposes: {
                "./ProductList": "./src/components/ProductList",
                "./ProductDetail": "./src/components/ProductDetail",
            },
            shared: {
                react: { singleton: true, eager: false },
                "react-dom": { singleton: true, eager: false },
            },
        }),
    ],
};

在消费远程组件时,使用 React.lazy 实现按需加载:

const ProductList = React.lazy(() => import("catalog/ProductList"));

function App() {
    return (
        <Suspense fallback={<Loading />}>
            <ProductList />
        </Suspense>
    );
}

踩坑经验:共享依赖版本冲突是最常见的问题,我们通过严格锁定 React 版本和配置 singleton 解决。另外,远程组件的类型安全需要通过 TypeScript 的 path mapping 和类型包发布来保障。