@aniyajs/rotor
Version:
基于webpack5开发的一款专注于打包、运行的工具
112 lines (101 loc) • 3.15 kB
JavaScript
const fs = require("fs-extra");
const path = require("path");
const { aRecursive } = require("./common");
const chalk = require("chalk");
const prettyBytes = require("pretty-bytes");
const gzipSize = require("gzip-size").sync;
async function printFileSizesAfterBuild(webpackStats, rootPath, appPath) {
try {
let files = await aRecursive(rootPath);
files = files
.filter((fileRelativePath) =>
/\.(css|js)$/.test(path.extname(fileRelativePath)),
)
.map((fileRelativePath) => {
const fileResolvePath = path
.relative(appPath, fileRelativePath)
.replace("//", "/");
const size = fs.statSync(fileResolvePath).size;
const gzipped = gzipSize(fs.readFileSync(fileRelativePath));
return {
fileResolvePath,
size,
gzipped,
};
});
// 文件名列的宽度
const fileWidth = 40;
const cssFiles = [];
const jsNFiles = [];
const jsEFiles = [];
// 输出表头
console.log(
`${chalk.cyan("File".padEnd(fileWidth + 8))} ${chalk.cyan(
"Size".padEnd(15),
)} ${chalk.cyan("Gzipped".padEnd(15))}`,
);
console.log();
files.forEach((fileInfo) => {
if (fileInfo.fileResolvePath.endsWith(".css")) {
cssFiles.push({
...fileInfo,
color: "blue",
});
} else if (fileInfo.size > 1024 * 1024) {
jsEFiles.push({
...fileInfo,
color: "yellow",
});
} else {
jsNFiles.push({
...fileInfo,
color: "green",
});
}
});
// 输出文件信息
[...jsEFiles, ...jsNFiles, ...cssFiles].forEach(
({ fileResolvePath, size, gzipped, color }) => {
// 按照文件名列的宽度进行换行
const fileLines = fileResolvePath.match(
new RegExp(`.{1,${fileWidth}}`, "g"),
) || [fileResolvePath];
fileLines.forEach((line, index) => {
if (index === 0) {
console.log(
`${chalk[color](line.padEnd(fileWidth + 8))} ${prettyBytes(
size,
).padEnd(15)} ${prettyBytes(gzipped).padEnd(15)}`,
);
} else {
console.log(chalk[color](line));
}
});
},
);
console.log();
// eslint-disable-next-line quotes
console.log(chalk.gray(` Images and other types of assets omitted.`));
console.log();
console.log();
console.log(
chalk.yellow("The bundle size is significantly larger than recommended."),
);
console.log(
chalk.yellow(
"Consider reducing it with code splitting: https://gitee.com/new-aniyajs/rotor",
),
);
console.log(
chalk.yellow(
"You can also analyze the project dependencies using ANALYZE=1",
),
);
console.log();
} catch (error) {
console.log(chalk.yellow("Warning: Failed to print file sizes."), error.message || error);
}
}
module.exports = {
printFileSizesAfterBuild,
};