Skip to content

模块联邦

@module-federation/vite

文档地址https://module-federation.io/zh/
推荐尝试@module-federation/bridge-vue3

配置示例

Remote(子模块)

ts
import { federation } from "@module-federation/vite";

federation({
  name: "remote",
  filename: "remoteEntry.js",
  exposes: {
    "./Button": "./src/App.vue",
  },
  remotes: {},
});

Host(主应用)

ts
federation({
  name: "host",
  remotes: {
    remote: {
      type: "module",
      name: "remote",
      entry: "http://localhost:3001/remoteEntry.js",
      entryGlobalName: "remote",
      shareScope: "default",
    },
  },
  exposes: {},
  filename: "remoteEntry.js",
});

使用远程组件

vue
<script setup>
import { defineAsyncComponent } from "vue";

const RemoteButtonAsync = defineAsyncComponent(() => import("remote/Button"));
</script>

<template>
  <RemoteButtonAsync />
</template>

通用配置(Host / Remote 共用)

ts
shared: ["vue", "vue-router", "axios"];

@originjs/vite-plugin-federation(社区版本)

社区维护的 Vite 插件实现,功能类似但生态和更新节奏略有不同。


其他概念

共享依赖(shared

  1. 打包去重:依赖仅打包一次,避免重复加载。
  2. Vue 实例一致性:在 Vue 环境中若不共享依赖,会导致多个 Vue 实例,破坏响应式系统。
  3. 避免全局污染:统一依赖版本,防止冲突。

CSS 隔离

  • 推荐使用 CSS Modules、Scoped CSS 或 Shadow DOM 等方案,防止样式互相干扰。

JS 隔离

  • 利用 ESM 的模块作用域天然隔离。
  • 注意全局变量(如 window.xxx)可能造成污染,应尽量避免。

模块联邦的常见问题

  1. 代码混淆需关闭

    ts
    minify: false; // 避免 Host 与 Remote 构建结果不一致导致运行时错误
  2. 组件库按需加载的兼容性问题

    • 若将某些 UI 库(如 Element Plus、Ant Design Vue)设为 shared,其内部按需引入的组件可能因 tree-shaking 行为不一致而失效。
    • 建议:对复杂组件库谨慎共享,或确保 Host 与 Remote 使用完全相同的构建配置和版本。