For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/config/test/federation.md.
close
  • 简体中文
  • federation

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

    是否启用 Module Federation 支持。

    Rstest 在 Node Mode 和 Browser Mode 中均支持 Module Federation。基于 Node 的 runner,包括 testEnvironment: 'node' 以及 jsdomhappy-dom 等 DOM 模拟环境,会使用 Rstest 的兼容垫片来支持通过 Node API 加载 chunk 的 federation runtime;Node Mode 支持从 Rstest 0.11.4 开始提供。Browser Mode 则使用 bundler 的 Web federation runtime,并需要 Rstest 0.11.10 或更高版本。

    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。
    • 面向 Node 的 federation 运行会使用 Rstest 的 CommonJS worker loader;Rstest 会将 output.chunkLoading 强制为 'require',使 async chunks 通过 Rstest 的模块加载器从内存构建产物中加载,而不经过文件系统。
    CLI
    rstest.config.ts
    npx rstest --federation

    测试联邦化应用

    federation 只负责准备测试运行时,不会配置 remotes、exposes 或共享模块。使用 @module-federation/rstest 时,该插件会配置 Module Federation 构建,并为基于 Node 的测试环境自动启用 Rstest 兼容模式,因此不要再设置 federation: true

    安装方式和 Rstest 测试流程,请先阅读 Module Federation 指南。复用已有 Rsbuild federation 配置以及完整插件选项,请参考 Rstest 官方集成指南

    rstest.config.ts
    import { federation } from '@module-federation/rstest';
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      plugins: [
        federation({
          name: 'main_app',
          remotes: {
            'component-app': 'component_app@http://localhost:3001/remoteEntry.cjs',
          },
          shared: {
            react: { singleton: true },
          },
        }),
      ],
    });

    该 Node 示例消费面向 Node 的 remoteEntry.cjs,Browser Mode 应消费浏览器构建的 remoteEntry.js。两者的区别请参考 Module Federation 指南;包含 Browser Mode、HTTP remote、本地 CommonJS remote 以及 SSR 测试的完整配置可参考 federation 示例