示例工程 27-framework-comparison
27-framework-comparison/demo-02-bundle-size/bundle.ts
import fs from "node:fs";
import path from "node:path";
import zlib from "node:zlib";
type Measurement = {
file: string;
raw: number;
gzip: number;
ratio: number;
};
function measure(file: string): Measurement {
const buffer = fs.readFileSync(file);
const gzip = zlib.gzipSync(buffer, { level: 9 }).byteLength;
return {
file: path.basename(file),
raw: buffer.byteLength,
gzip,
ratio: buffer.byteLength === 0 ? 0 : gzip / buffer.byteLength,
};
}
const fixtureDir = path.join(process.cwd(), "fixtures");
const args = process.argv.slice(2).filter((arg) => !arg.startsWith("--"));
const files =
args.length > 0
? args
: ["app.js", "app.css"].map((name) => path.join(fixtureDir, name));
const measurements = files.map(measure);
const totalRaw = measurements.reduce((sum, item) => sum + item.raw, 0);
const totalGzip = measurements.reduce((sum, item) => sum + item.gzip, 0);
const repetitive = zlib.gzipSync(Buffer.alloc(64 * 1024, 65), {
level: 9,
}).byteLength;
const random = zlib.gzipSync(
Buffer.from(
Array.from({ length: 64 * 1024 }, (_, index) => (index * 37) % 251),
),
{ level: 9 },
).byteLength;
console.log(
JSON.stringify({
evt: "smoke",
ok:
measurements.length > 0 &&
measurements.every((item) => item.gzip > 0 && item.gzip < item.raw) &&
totalGzip > 0 &&
totalGzip < totalRaw &&
repetitive < random,
totalRaw,
totalGzip,
ratio:
totalRaw === 0 ? 0 : Math.round((totalGzip / totalRaw) * 1000) / 1000,
measurements,
repetitive,
random,
}),
);