rollup-plugin-stats
Version:
Output Rollup stats
81 lines (75 loc) • 2.5 kB
JavaScript
import path from 'node:path';
import process from 'node:process';
import extractRollupStats from './extract.mjs';
import fs from 'node:fs/promises';
async function rollupStatsWrite(filepath, stats) {
const content = JSON.stringify(stats, null, 2);
// Create base directory if it does not exist
await fs.mkdir(path.dirname(filepath), { recursive: true });
await fs.writeFile(filepath, content);
return {
filepath,
content,
};
}
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 PLUGIN_NAME = 'rollupStats';
const DEFAULT_FILE_NAME = 'stats.json';
function rollupStats(options = {}) {
return {
name: PLUGIN_NAME,
async generateBundle(context, bundle) {
const resolvedOptions = typeof options === 'function' ? options(context) : options;
const { fileName, stats: statsOptions, write = rollupStatsWrite } = resolvedOptions || {};
const resolvedFileName = fileName || DEFAULT_FILE_NAME;
const filepath = path.isAbsolute(resolvedFileName)
? resolvedFileName
: path.join(context.dir || process.cwd(), resolvedFileName);
const stats = extractRollupStats(bundle, statsOptions);
try {
const res = await write(filepath, stats);
const outputSize = Buffer.byteLength(res.content, 'utf-8');
this.info(`Stats saved to ${res.filepath} (${formatFileSize(outputSize)})`);
}
catch (error) { // eslint-disable-line
// Log error, but do not throw to allow the compilation to continue
this.warn(error);
}
},
};
}
export { rollupStats as default };
//# sourceMappingURL=index.mjs.map