rollup-plugin-webpack-stats
Version:
Rollup/Vite/Rolldown plugin to generate a stats JSON file with a bundle-stats webpack-compatible structure
62 lines (60 loc) • 1.73 kB
JavaScript
import path from "node:path";
import crypto from "node:crypto";
//#region src/utils.ts
const HASH_LENGTH = 7;
/**
* Get content byte size
*/
function getByteSize(content) {
if (!content) return 0;
if (typeof content === "string") return Buffer.byteLength(content);
return content?.length || 0;
}
/**
* Generate a 7 chars hash from a filepath
*/
function getHash(filepath) {
return crypto.createHash("sha256").update(filepath).digest("hex").substr(0, HASH_LENGTH);
}
function getChunkId(chunk) {
let value = chunk.name;
if (chunk.moduleIds?.length > 0) {
const absoluteModulePath = chunk.moduleIds[chunk.moduleIds.length - 1];
value = path.relative(process.cwd(), absoluteModulePath);
}
return getHash([chunk, value].join("-"));
}
function round(value, precision = 2) {
const multiplier = 10 ^ precision;
return Math.round(value * multiplier) / multiplier;
}
const FILE_SIZE = {
BYTE: {
symbol: "B",
multiplier: 1
},
KILO: {
symbol: "KiB",
multiplier: 1024
},
MEGA: {
symbol: "MiB",
multiplier: 1024 * 1024
}
};
function formatFileSize(value) {
let unit = FILE_SIZE.BYTE;
if (typeof value !== "number") return `0${unit.symbol}`;
if (value < FILE_SIZE.KILO.multiplier) unit = FILE_SIZE.BYTE;
else if (value < FILE_SIZE.MEGA.multiplier) unit = FILE_SIZE.KILO;
else unit = FILE_SIZE.MEGA;
return `${round(value / unit.multiplier, 2)}${unit.symbol}`;
}
const DEFAULT_FILE_NAME = "webpack-stats.json";
function resolveFilepath(fileName = DEFAULT_FILE_NAME, outputDir) {
if (path.isAbsolute(fileName)) return fileName;
return path.join(outputDir || process.cwd(), fileName);
}
//#endregion
export { formatFileSize, getByteSize, getChunkId, resolveFilepath };
//# sourceMappingURL=utils.mjs.map