Files
suaveplan/packages/devtools/tooling/test-vite/src/bundle-size-snapshot/bundle-size-snapshot.md
2026-05-27 23:47:53 +01:00

2.4 KiB

bundle-size-snapshot

(no submodules)

Purpose

snapshotBundleSize compares the byte size of an emitted bundle against a previously-recorded snapshot file and enforces a configurable growth tolerance. It is the bundle-size equivalent of a Vitest snapshot — when the bundle grows past tolerance the call throws TestViteError(TEST_VITE.SIZE_BUDGET_EXCEEDED) so CI fails with a clear diagnostic. Run with update: true from a developer machine to refresh the snapshot after an intentional change.

Features

  • Default 5% growth tolerance (tolerance: 0.05).
  • update: true mode writes the current size to the snapshot file.
  • Injectable filesystem adapter so the validator can run in environments without node:fs.
  • ENOENT-aware error mapping: missing snapshot → SNAPSHOT_MISSING; missing bundle → MISSING_ENTRY.
  • OTel counters: test_vite_validator_runs_total{kind="bundle_size"} per call, test_vite_validator_violations_total on budget violations.

Usage: Basic

import { readFile, writeFile } from "node:fs/promises";
import { snapshotBundleSize } from "@suaveplan/test-vite/bundle-size-snapshot";

const fs = {
  readFile: (p: string) => readFile(p),
  writeFile: (p: string, data: string) => writeFile(p, data, "utf8"),
};

await snapshotBundleSize({
  entry: "dist/index.js",
  snapshot: "dist/index.size.snap",
  fs,
});

Usage: Advanced

Refresh the snapshot after a deliberate change:

await snapshotBundleSize({
  entry: "dist/index.js",
  snapshot: "dist/index.size.snap",
  tolerance: 0.02,
  update: true,
  fs,
});

API Reference

  • snapshotBundleSize(opts: SnapshotBundleSizeOptions): Promise<BundleSizeResult>.
  • SnapshotBundleSizeOptions — { entry, snapshot, tolerance?, update?, fs }.
  • BundleSizeResult — { updated: boolean, size: number, delta?: number }.
  • Throws TestViteError with TEST_VITE.INVALID_OPTIONS, TEST_VITE.MISSING_ENTRY, TEST_VITE.SNAPSHOT_MISSING, or TEST_VITE.SIZE_BUDGET_EXCEEDED.

Implementation Notes

The snapshot file stores a single decimal integer — the byte count of the last accepted bundle. Whitespace is trimmed before parsing so editors that auto-add a trailing newline do not break the comparison. Read failures on the snapshot are uniformly classified as SNAPSHOT_MISSING whether the cause is ENOENT or another IO error so the diagnostic stays consistent across platforms.