如何按页面统计 Babel 引入的 helper 体积

解读

国内线上环境普遍要求“首屏 200 KB 以内”“二跳 500 KB 以内”,而 Babel 的 helpers(如 _classCallCheck、_inherits、_asyncToGenerator 等)一旦重复打包,体积会迅速膨胀。面试官想知道:

  1. 你是否理解 helpers 的注入机制(runtime vs inline);
  2. 能否把“按页面”这个维度落地,而不是只给出一个总包体积;
  3. 是否熟悉国内主流构建(Webpack、Rspack、Vite)的插件写法,能把统计结果精确映射到 HTML 入口,最终产出一份“页面维度”的审计报告,方便产品、运维、CDN 预算三方拍板。

知识点

  1. Babel helper 三种注入模式

    • helpers: "inline":每个文件硬编码,体积最大。
    • helpers: "runtime":统一 @babel/runtime 引入,可复用。
    • @babel/plugin-transform-runtime + corejs:把 polyfill 也 runtime 化。
  2. 国内常用构建的模块图数据结构

    • Webpack/Rspack:compilation.chunkGraph.getModuleChunks(module)、chunkGraph.getChunkModules(chunk)。
    • Vite(Rollup):bundle[chunkName].modules。
  3. 国内 CDN 惯例:一个 HTML 对应一个或多个异步 Chunk,但“页面”=“HTML 入口”,因此需要维护 htmlName → [syncChunk, asyncChunk...] 的映射。

  4. 精确计算 helper 体积的边界

    • 只算 @babel/runtime/helpers/esm/* 或 babel-runtime/helpers/* 的代码量,不算映射文件。
    • 要减去 gzip/brotli 后体积,因为国内云厂商按压缩后计费。
  5. 合规与性能

    • 统计插件必须缓存,不能拖慢 CI;
    • 结果要落盘到 .babel-helper-audit.json,供后续 CR 平台展示。

答案

步骤一:锁定 helpers 来源

pnpm why @babel/runtime

确认项目已切到 "runtime" 模式,否则先全局替换 preset-env 配置:

{
  presets: [
    ['@babel/preset-env', { targets: { chrome: 58 }, helpers: true }]
  ],
  plugins: [
    ['@babel/plugin-transform-runtime', { corejs: 3, helpers: true }]
  ]
}

步骤二:在构建层注册一个“页面维度”采集插件
以 Webpack5 为例(Rspack 同构),新建 babel-helper-stats-plugin.js:

const { gzipSync } = require('zlib');
const { basename } = require('path');

class BabelHelperStatsPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync('BabelHelperStats', (compilation, cb) => {
      const pageMap = {}; // htmlName -> { raw: 0, gzip: 0, helpers: new Set() }

      // 1. 建立 html → chunks 映射(国内多页应用)
      for (const asset of Object.keys(compilation.assets)) {
        if (!asset.endsWith('.html')) continue;
        const htmlName = basename(asset, '.html');
        const chunkNames = Array.from(
          compilation.entrypoints.get(htmlName).chunks,
          c => c.name || c.id
        );
        pageMap[htmlName] = { raw: 0, gzip: 0, helpers: new Set() };
      }

      // 2. 遍历模块,过滤 babel runtime helpers
      for (const module of compilation.modules) {
        if (!module.resource) continue;
        const isHelper = /[\\/]@babel[\\/]runtime[\\/]helpers[\\/]esm[\\/]/.test(module.resource);
        if (!isHelper) continue;

        const helperName = basename(module.resource, '.js');
        const helperSize = Buffer.byteLength(module._source?.source() || '', 'utf8');

        // 3. 反向查出哪些 chunk 引用了该 helper
        const chunks = compilation.chunkGraph.getModuleChunks(module);
        for (const c of chunks) {
          for (const [page, info] of Object.entries(pageMap)) {
            if (pageMap[page].chunks?.includes(c.name || c.id)) {
              info.helpers.add(helperName);
              info.raw += helperSize;
            }
          }
        }
      }

      // 4. 计算 gzip 体积并写报告
      for (const [page, info] of Object.entries(pageMap)) {
        const concatCode = Array.from(info.helpers).join('\n');
        info.gzip = gzipSync(concatCode).length;
      }

      const out = JSON.stringify(pageMap, null, 2);
      compilation.assets['babel-helper-audit.json'] = {
        source: () => out,
        size: () => Buffer.byteLength(out)
      };
      cb();
    });
  }
}

在 webpack.config.js 里 plugins: [new BabelHelperStatsPlugin()],执行 npm run build 后即可在 dist 目录拿到 babel-helper-audit.json,样例:

{
  "home": { "raw": 14230, "gzip": 4120, "helpers": ["asyncToGenerator","objectSpread2"] },
  "product": { "raw": 8150, "gzip": 2390, "helpers": ["classCallCheck","createClass"] }
}

步骤三:持续治理
把 gzip 体积推送到内部蓝盾 / 飞书群机器人,超 5 KB 的页面自动创建 Issue,指派对应前端 Owner 进行

  • 拆异步块,让 helper 进 vendor-babel 长效缓存;
  • 或者把高频 helper 提前注入 window._babelHelpers_,利用国内 CDN 强缓存,进一步削减重复。

拓展思考

  1. 若项目已全量接入 Vite,可写 Rollup 插件 generateBundle 阶段做同样统计;注意 Rollup 的 bundle[chunkName].modules 是打平结构,需要额外解析 importer 图才能还原“页面”维度。
  2. 对于 SSR 场景(Next.js、Remix),页面是动态路由,可在 getServerSideProps 里把 babel-helper-audit.json 读进内存,实时下发到前端,用于“运行时”按页懒加载 helpers,进一步节省边缘节点流量。
  3. 国内小程序容器(微信、支付宝)同样用 Babel,但无传统 Chunk 概念,可以把 helpers 体积统计下沉到“分包”维度,利用开发者工具 CI 的 miniprogram-ci 在 beforeUpload 钩子内完成审计,防止主包超限 2 MB。