audit-bundle-size.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env node
  2. import { stat } from "node:fs/promises";
  3. import { extname, resolve } from "node:path";
  4. const argv = process.argv.slice(2);
  5. function readArg(name) {
  6. const index = argv.indexOf(name);
  7. if (index === -1) {
  8. return null;
  9. }
  10. return argv[index + 1] ?? null;
  11. }
  12. const artifactPath = readArg("--artifact-path");
  13. if (!artifactPath) {
  14. throw new Error("Usage: audit-bundle-size.mjs --artifact-path <path-to-artifact>");
  15. }
  16. const absoluteArtifactPath = resolve(artifactPath);
  17. const limitsMb = {
  18. default: 500,
  19. // Windows-only 精简:仅保留 .exe(NSIS 安装包)产物预算。
  20. ".exe": 500,
  21. };
  22. function formatMiB(bytes) {
  23. return `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
  24. }
  25. const artifactStat = await stat(absoluteArtifactPath);
  26. const extension = extname(absoluteArtifactPath).toLowerCase();
  27. const limit = limitsMb[extension] ?? limitsMb.default;
  28. const sizeMiB = artifactStat.size / 1024 / 1024;
  29. console.log(`Artifact: ${absoluteArtifactPath}`);
  30. console.log(`Type: ${extension || "<no-extension>"}`);
  31. console.log(`Size: ${formatMiB(artifactStat.size)}`);
  32. console.log(`Limit: ${limit} MiB`);
  33. if (sizeMiB > limit) {
  34. console.error("Bundle size audit failed:");
  35. console.error(` - Artifact exceeds ${limit} MiB`);
  36. process.exit(1);
  37. }