close

federation

  • 类型: boolean
  • 默认值: false
  • CLI: --federation

是否启用 Module Federation 兼容模式。

该选项适用于 Rstest 基于 Node 的 runner,包括 testEnvironment: 'node' 以及 jsdomhappy-dom 等 DOM 模拟环境。它不会启用或改变 Rstest Browser Mode(browser.enabled: true)。

Rstest 在单个 worker 运行时中执行测试产物,以保证模块 mock 始终生效。而 Module Federation 运行时会自行加载远程入口和 chunk —— 通过 Node 的 fs/vm/eval 或 HTTP —— 这发生在该运行时之外。启用 federation 后,Rstest 会安装额外的运行时垫片,让两者协同工作:

  • 为外部化的动态导入提供 globalThis 兜底实现,使通过 vm/eval 执行的 federation 运行时 chunk 仍能使用 Node 原生动态导入加载模块。
  • 防止 Module Federation 的占位 chunk 处理器(consumes / remotes)在 federation 运行时初始化前抛出异常。
  • 阻止 federation 运行时插件替换 Rstest 的 chunk 加载处理器,否则 chunk 会在测试运行时之外执行并丢失 mock。
CLI
rstest.config.ts
npx rstest --federation

测试联邦化应用

federation 只负责准备测试运行时。Module Federation 构建本身(remotes、exposes、共享模块)通过 bundler 插件配置,例如 @module-federation/rstest,它会将 federation 配置应用到 Rstest 的构建中:

rstest.config.ts
import { federation } from '@module-federation/rstest';
import { defineConfig } from '@rstest/core';

export default defineConfig({
  federation: true,
  plugins: [
    federation({
      name: 'main_app',
      remotes: {
        'component-app': 'component_app@http://localhost:3001/remoteEntry.js',
      },
      shared: {
        react: { singleton: true },
      },
    }),
  ],
});

完整的配置示例(HTTP 远程、本地 CommonJS 远程以及 SSR 测试)可参考 federation 示例