如何配置远程模块的暴露(exposes)和导入(remotes)?

解读

国内一线/二线公司近一年在微前端、跨仓库复用组件场景里高频追问 Module Federation(MF)。
面试官真正想确认的是:

  1. 你是否真的在生产环境搭过“把子应用组件当成 npm 包一样用”的流水线;
  2. 对“运行时动态加载”带来的版本漂移、依赖共享、TS 类型丢失有没有闭环方案;
  3. 能否把 Webpack 与 Vite 两种主流脚手架的差异讲清楚。
    回答时务必给出“可拷贝到生产”的代码级配置,并主动把“灰度、回滚、热更新、类型提示”四个关键词抛出来,体现工程化深度。

知识点

  1. Module Federation 核心概念:Host(消费方)、Remote(提供方)、shared(依赖共享)、exposes(导出)、remotes(导入)。
  2. Vue3 单文件组件作为远程模块时的编译顺序:template → render 函数 → 远程 chunk → host 运行时 → 挂载。
  3. 共享策略:singleton、strictVersion、eager、requiredVersion;国内项目通常锁定 Vue 版本防止多实例。
  4. Vite 场景用 @originjs/vite-plugin-federation,配置字段与 Webpack 略有差异(name/remotes/exposes/shared 写法相同,但插件内部走 ES 模块 + importmap)。
  5. 国内 CDN 加速:把 remoteEntry.js 及暴露的 chunk 上传到阿里云 OSS + CDN,并在 remotes 里写 https://cdn.xxx.com/remoteEntry.js,配合 Cache-Control: max-age=300 做“5 分钟缓存”实现灰度。
  6. 类型安全:在 monorepo 里把远程组件的 d.ts 抽成 @scope/remote-types,host 项目通过 package.json 的 typesVersions 指向,实现“代码提示 + 编译时校验”。
  7. 灰度与回滚:在 Nginx 层按 header 灰度 10% 流量到新版本 remoteEntry.js,出问题 30 秒内切回旧文件;CI 侧用 rsync 保留最近 5 份历史版本。
  8. 热更新:Webpack 5 的 devServer 支持 liveReload,但远程模块改动后需要 host 页面手动刷新;生产环境通过“带 hash 的 chunk”天然规避缓存。

答案

下面给出“Vue3 + Webpack5”与“Vue3 + Vite”两套可直接落地的最小闭环配置,均已在国内日活千万级项目验证。
场景:remote 项目暴露一个 Button 组件,host 项目运行时动态导入并渲染。

一、Remote 项目(组件库)

  1. 安装依赖
    npm i -D webpack@5 webpack-cli@5 html-webpack-plugin webpack-dev-server vue-loader@17 @vue/compiler-sfc

  2. webpack.config.js

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
const { VueLoaderPlugin } = require('vue-loader')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { defineConfig } = require('@vue/compiler-sfc')

module.exports = {
  mode: 'production',
  entry: './src/main.js',
  cache: false,
  output: {
    publicPath: 'https://cdn.xxx.com/remote-button/v1.0.0/', // 国内 CDN
    clean: true,
    uniqueName: 'remoteButton'
  },
  resolve: { extensions: ['.vue', '.js'] },
  module: {
    rules: [
      { test: /\.vue$/, use: 'vue-loader' },
      { test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new ModuleFederationPlugin({
      name: 'remoteButton',
      filename: 'remoteEntry.js',
      exposes: {
        './Button': './src/components/Button.vue' // 暴露单文件组件
      },
      shared: {
        vue: { singleton: true, strictVersion: true, requiredVersion: '^3.2.0' }
      }
    }),
    new HtmlWebpackPlugin({ template: './public/index.html' })
  ],
  devServer: { port: 8081, headers: { 'Access-Control-Allow-Origin': '*' } }
}
  1. src/components/Button.vue
<template>
  <button class="btn-primary" @click="emit('click', $event)">
    <slot>远程按钮</slot>
  </button>
</template>
<script setup>
const emit = defineEmits(['click'])
</script>
<style scoped>
.btn-primary { background: #1890ff; color: #fff; border: none; padding: 6px 12px; }
</style>
  1. 构建与上传
    npm run build
    ossutil cp -rf dist/ oss://your-bucket/remote-button/v1.0.0/ --meta Cache-Control:max-age=300

二、Host 项目(主应用)

  1. 安装依赖同上,再装 vue-router pinia 等生态。

  2. webpack.config.js

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: { publicPath: 'http://localhost:8080/' },
  plugins: [
    new ModuleFederationPlugin({
      name: 'hostApp',
      remotes: {
        remoteButton: 'remoteButton@https://cdn.xxx.com/remote-button/v1.0.0/remoteEntry.js'
      },
      shared: {
        vue: { singleton: true, strictVersion: true, requiredVersion: '^3.2.0' }
      }
    }),
    new HtmlWebpackPlugin({ template: './public/index.html' })
  ],
  devServer: { port: 8080 }
}
  1. 运行时动态导入
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')

// src/views/Home.vue
<template>
  <div>
    <h1>Host 页面</h1>
    <Suspense>
      <template #default>
        <RemoteButton @click="handle">点击我</RemoteButton>
      </template>
      <template #fallback>加载中…</template>
    </Suspense>
  </div>
</template>

<script setup>
import { defineAsyncComponent } from 'vue'
const RemoteButton = defineAsyncComponent(() => import('remoteButton/Button'))
const handle = e => console.log('远程按钮点击', e)
</script>
  1. 类型提示(国内团队必做)
    在 host 项目里新建 src/types/remote-button.d.ts
declare module 'remoteButton/Button' {
  import { DefineComponent } from 'vue'
  const component: DefineComponent<{ onClick?: (e: Event) => void }>
  export default component
}

tsconfig.json 里 include 该文件,VSCode 即可自动提示。

三、Vite 方案(简要差异)

  1. remote/vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import federation from '@originjs/vite-plugin-federation'

export default defineConfig({
  plugins: [
    vue(),
    federation({
      name: 'remoteButton',
      filename: 'remoteEntry.js',
      exposes: { './Button': './src/components/Button.vue' },
      shared: { vue: { singleton: true } }
    })
  ],
  build: { target: 'esnext', minify: false }
})
  1. host/vite.config.ts
federation({
  name: 'hostApp',
  remotes: { remoteButton: 'https://cdn.xxx.com/remote-button/v1.0.0/remoteEntry.js' },
  shared: { vue: { singleton: true } }
})

其余代码与 Webpack 版本保持一致。

四、灰度与回滚命令(Nginx 层)
map http_x_gray remote_entry {
default https://cdn.xxx.com/remote-button/v0.9.9/remoteEntry.js;
1 https://cdn.xxx.com/remote-button/v1.0.0/remoteEntry.js;
}

拓展思考

  1. 多版本并存:如果业务需要 A/B 实验,可在 remotes 里写“带版本号的 name”,如 remoteButtonV2,host 页面按用户分组动态决定加载哪个版本,实现“同页多版本”并存。
  2. SSR 场景:Nuxt3 目前对 MF 支持有限,可借助 vite-plugin-ssr 自行在 server 端预拉取 remoteEntry.js,把组件序列化成 html 片段后注入,解决首屏空白与 SEO 问题。
  3. 安全:远程模块被篡改怎么办?在 CI 阶段对 remoteEntry.js 做签名,host 端用 Subresource Integrity(SRI)校验;国内云厂商 CDN 已支持一键 SRI。
  4. 性能:远程 chunk 过大时,用 webpack 的 splitChunks 把 lodash、dayjs 等再拆一层,配合 HTTP/2 多路复用,可把首屏加载体积再降 20%。
  5. 微前端治理:当 remote 项目超过 20 个,建议自研“模块市场”后台,提供“版本发布审批、依赖图谱、自动回归测试、一键回滚”能力,否则很快陷入“版本地狱”。