如何测试 Vite 的“预构建”耗时?

解读

国内前端工程普遍把 Vite 作为 Webpack 的替代方案,预构建(Pre-Bundle)又是 Vite 冷启动链路里最不可控的一环。面试官抛出这道题,核心想验证三件事:

  1. 你是否理解预构建的触发时机与产物缓存策略;
  2. 能否把“耗时”这一非功能性指标转化为可重复、可断言的测试用例;
  3. 是否熟悉 Jest 在 Node 侧做集成测试的最佳实践(钩子、生命周期、Mock、快照、性能断言)。

一句话:不是让你手动掐秒表,而是让 Jest 自动、稳定、可回归地“掐秒表”,并且把结果写进 CI。

知识点

  1. Vite 预构建触发条件
    • 首次启动、依赖版本变更、force 选项、optimizeDeps 配置变动、deps 缓存文件被删除。
  2. 耗时采集点
    • optimizeDeps 内部日志:「optimized dependencies in xxxms」;
    • ViteDevServer 的 configureServer 钩子,可注入自定义计时器;
    • 进程级高精度时间:process.hrtime.bigint()。
  3. Jest 测试分类
    • 单元测试:mock 掉真正的预构建,只测自己写的计时钩子逻辑;
    • 集成测试:拉起真实 ViteDevServer,采集 wall time 并断言阈值;
    • 基准测试(Benchmark):多次预热后取 P50 / P95,防止偶发抖动。
  4. 稳定性手段
    • 使用 jest-slow-test-reporter 把超时用例标红;
    • 在 CI 里固定 Node 版本、yarn.lock、系统负载、--runInBand 串行;
    • 利用 jest.setTimeout 与 beforeAll 生命周期,保证缓存预热。
  5. 覆盖率与回归
    • 把阈值写进 jest.config.js 的 performance 全局属性,后续迭代只能收紧不能放宽;
    • 快照测试可锁定预构建产物 hash,防止“性能退化”由缓存失效引发。

答案

下面给出可直接落地到国内 GitLab CI 的 Jest 集成测试方案,分三步:计时埋点、测试用例、性能断言。

  1. 计时埋点(vite-plugin-time-opt)
// plugins/vite-plugin-time-opt.js
export default function timeOptPlugin() {
  let start;
  return {
    name: 'time-opt',
    configResolved(config) {
      // 仅在开发阶段生效
      if (config.command !== 'serve') return;
      // 清理旧缓存,强制触发预构建
      const depsCacheDir = path.resolve(config.cacheDir, 'deps');
      if (fs.existsSync(depsCacheDir)) {
        fs.rmSync(depsCacheDir, { recursive: true, force: true });
      }
    },
    buildStart() {
      start = process.hrtime.bigint();
    },
    configureServer(server) {
      server.middlewares.use('/__perf', (req, res) => {
        const cost = Number(process.hrtime.bigint() - start) / 1e6; // ms
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ prebundleMs: cost }));
      });
    }
  };
}
  1. 测试用例(tests/prebundle-perf.spec.js)
import { createServer } from 'vite';
import got from 'got';

const THRESHOLD = 3000; // 3s 以内,可按项目调整
let server, port;

beforeAll(async () => {
  server = await createServer({
    configFile: false,
    root: path.join(__dirname, '../demo'),
    plugins: [timeOptPlugin()],
    server: { port: 0 } // 随机端口
  });
  await server.listen();
  port = server.config.server.port;
}, 30000);

afterAll(async () => {
  await server.close();
});

test('预构建耗时应在阈值以内', async () => {
  // 触发预构建
  await got(`http://localhost:${port}/__perf`);
  // 采集耗时
  const { body } = await got(`http://localhost:${port}/__perf`, { responseType: 'json' });
  const { prebundleMs } = body;
  expect(prebundleMs).toBeGreaterThan(0);
  expect(prebundleMs).toBeLessThan(THRESHOLD);
});
  1. 性能断言与回归
    在 jest.config.js 中增加
global.performance = { THRESHOLD };

后续迭代若依赖膨胀导致耗时上升,CI 会直接失败,倒逼开发拆分依赖或开启 cdn 外链。

拓展思考

  1. 多轮预热与 P95 断言
    单点采样容易受机器负载抖动,可在 beforeAll 里循环 5 次取排序后的 95% 分位,写成
    expect(p95).toBeLessThan(THRESHOLD)。
  2. 与 Lighthouse-CI 联动
    把预构建耗时作为自定义指标打到 Lighthouse 的 “metrics” 字段,统一看板,防止“开发阶段快、生产阶段慢”。
  3. 缓存命中率监控
    在插件里记录 hash 命中次数,用 Jest 快照比对 hash 文件,一旦依赖版本没变却触发重新构建,快照测试失败,提前发现配置误写。
  4. 并行流水线优化
    若仓库采用 Monorepo,可在 GitLab CI 里把预构建耗时测试单独放到 “performance” stage,与单元测试并行跑,失败再阻塞 merge,兼顾效率与质量。