如何在 Gulp 构建中暴露 Module Federation 清单?

解读

国内前端面试中,Module Federation 是 Webpack5 的“杀手级”特性,而 Gulp 本身并不具备打包能力,只能借助 Webpack Stream、webpack-merge 等工具把 Webpack 的产出接入到 Gulp 管道。面试官真正想确认的是:

  1. 你是否理解 Gulp 只是任务编排器,真正的联邦模块打包仍需 Webpack 完成;
  2. 你是否能把 Webpack5 的 ModuleFederationPlugin 产出的 remoteEntry.js 与 mf-manifest.json 正确拷贝到可访问的静态目录,并保证 publicPath 与 CDN/边缘节点路径一致;
  3. 你是否能在 Gulp 管道里 动态重写 manifest 中的 publicPath,以适配国内常见的“多环境域名+版本号”发布策略;
  4. 你是否知道如何用 gulp-rev、gulp-rev-replace 或自写插件,把带 hash 的 remoteEntry 注入到 HTML 模板,供下游微前端基座消费。

一句话:让 Gulp 把 Webpack5 吐出的联邦清单“暴露”给浏览器可访问的 URL,同时保持版本可追踪、路径可配置。

知识点

  • Vinyl 文件对象:Gulp 管道中的虚拟文件,需通过 through2 或 transform 流处理;
  • Webpack5 ModuleFederationPlugin 配置项:name、filename、exposes、shared、library.type='var';
  • manifest 生成原理:ModuleFederationPlugin 默认不输出 json,需要二次插件(如 webpack-manifest-plugin 或自定义插件)把 exposes 映射表写成 mf-manifest.json;
  • publicPath 动态注入:国内项目常在 OSS+CDN 场景下使用 __CDN_HOST__/<version>/ 作为 publicPath,需在 Gulp 任务里根据 process.env.BUILD_ENV 动态替换;
  • 静态资源上传:利用 gulp-oss-upload、gulp-cos-upload 将 remoteEntry 与 manifest 推至腾讯云 COS 或阿里云 OSS,并返回可访问 URL;
  • 缓存与版本控制:remoteEntry 文件名带 [contenthash],manifest 文件名固定,方便基座通过 fetch('/static/mf-manifest.json') 拿到最新映射;
  • 跨域处理:CDN 需配置 Access-Control-Allow-Origin: *,否则基座请求 remoteEntry 会触发 CORS 错误;
  • 本地开发热更新:通过 gulp-webpack-dev-middleware 把 Webpack5 的 devServer 嵌入 Gulp,保证联邦模块在本地也能被 http://localhost:3001/remoteEntry.js 访问。

答案

  1. 在项目根目录安装依赖

    npm i -D webpack webpack-stream@latest webpack-cli@latest html-webpack-plugin@latest webpack-manifest-plugin@latest through2 gulp-rename gulp-if gulp-replace
    
  2. 在 webpack.federation.js 中声明联邦配置

    const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
    const ManifestPlugin = require('webpack-manifest-plugin').WebpackManifestPlugin;
    module.exports = (env) => ({
      output: {
        publicPath: env.cdnHost || 'https://cdn.example.com/mf/' // 国内 CDN 路径
      },
      plugins: [
        new ModuleFederationPlugin({
          name: 'components',
          filename: 'remoteEntry.[contenthash:8].js',
          exposes: {
            './Button': './src/components/Button/index.tsx'
          },
          shared: { react: { singleton: true }, 'react-dom': { singleton: true } }
        }),
        new ManifestPlugin({
          fileName: 'mf-manifest.json',
          filter: (f) => f.name.includes('remoteEntry')
        })
      ]
    });
    
  3. 在 gulpfile.js 中编排任务

    const { src, dest, series, parallel } = require('gulp');
    const webpack = require('webpack-stream');
    const rename = require('gulp-rename');
    const replace = require('gulp-replace');
    const through = require('through2');
    const path = require('path');
    
    function buildFederation() {
      return src('.')
        .pipe(webpack(require('./webpack.federation')(process.env)))
        .pipe(dest('dist/mf'));
    }
    
    function rewriteManifest() {
      return src('dist/mf/mf-manifest.json')
        .pipe(
          through.obj(function (file, _, cb) {
            const json = JSON.parse(file.contents.toString());
            // 根据国内灰度规则,把 publicPath 替换为带版本号的 CDN 地址
            const publicPath = `https://cdn.example.com/mf/${process.env.VERSION}/`;
            Object.keys(json).forEach((k) => {
              json[k] = publicPath + path.basename(json[k]);
            });
            file.contents = Buffer.from(JSON.stringify(json, null, 2));
            cb(null, file);
          })
        )
        .pipe(dest('dist/mf'));
    }
    
    function upload() {
      // 以腾讯云 COS 为例
      const cos = require('gulp-cos-upload');
      return src('dist/mf/**')
        .pipe(
          cos({
            Bucket: 'mf-assets-1250000000',
            Region: 'ap-shanghai',
            prefix: `mf/${process.env.VERSION}/`
          })
        );
    }
    
    exports.default = series(buildFederation, rewriteManifest, upload);
    
  4. 基座使用方式
    基座通过 fetch('https://cdn.example.com/mf/${version}/mf-manifest.json') 拿到 remoteEntry 的完整 URL,再动态注入 <script src="..."> 即可加载联邦模块。

拓展思考

  • 多团队并行发布:国内大厂常把 MF 作为“微前端物料市场”,需要 Gulp 任务在 CI 阶段把 manifest 写入 Redis 或 Nacos,供基座实时发现新版本;
  • 灰度与回滚:在 rewriteManifest 阶段把版本号写入 阿里云 MSE 标签,实现按用户维度灰度;
  • SSR 场景:remoteEntry 需同步上传到 Node 中间层,通过 require-from-string 在服务端直接引用,避免 hydration 失败;
  • 安全:remoteEntry.js 上传后,利用 腾讯云 SCF 边缘函数 做二次签名,防止 CDN 被刷流量;
  • 非 Webpack 方案:如果未来出现 Rspack 等国产打包器,Gulp 任务只需替换 webpack-stream 为 rspack-stream,暴露 manifest 的思路不变,但构建速度可提升 5~10 倍,适合国内“秒级发布”场景。