game-engine/rollup-plugins/bundle-size.mjs

62 lines
1.9 KiB
JavaScript

import path from "path";
import fs from "fs";
import chalk from "chalk";
export default function bundleSize({ file, maxSize = 13 }) {
return {
name: "rollup-plugin-bundle-size",
writeBundle: {
secuential: true,
order: "post",
async handler(options, bundle) {
let uncompressedSize = 0;
console.log(
chalk.green("Filename".padEnd(30, " ") + "\t Size (bytes).")
);
for (const file in bundle) {
const { modules } = bundle[file];
if (bundle[file].type === 'chunk') {
for (const moduleName in modules) {
const module = modules[moduleName];
const name = path.basename(moduleName);
uncompressedSize += module.renderedLength;
console.log(
`${chalk.cyan(name.padEnd(30, " "))}\t ${chalk.cyan(
module.renderedLength
)}`
);
}
} else if (bundle[file].type === 'asset') {
const { size } = fs.statSync(file);
uncompressedSize += size;
console.log(
`${chalk.cyan(file.padEnd(30, " "))}\t ${chalk.cyan(
size
)}`
);
}
}
console.log(
chalk.green(
"Total before compression " +
chalk.bold(chalk.green(uncompressedSize))
)
);
const asset = path.join(options.dir, file);
const { size } = fs.statSync(asset);
const percent = parseInt((size / (maxSize * 1024)) * 100, 10);
const color =
percent < 50 ? chalk.green : percent < 80 ? chalk.yellow : chalk.red;
console.log(
`Created bundle ${chalk.cyan(asset)}: ${chalk.bold(
chalk.cyan(size)
)} bytes, ${color(percent + "%")} of total game size used.`
);
},
},
};
};