2022-01-27 11:16:50 +08:00
|
|
|
import fs from "node:fs/promises";
|
|
|
|
|
import { visualizer as esbuildVisualizer } from "esbuild-visualizer/dist/plugin/index.js";
|
|
|
|
|
|
2022-01-27 16:53:07 +08:00
|
|
|
export default function esbuildPluginVisualizer({ formats }) {
|
|
|
|
|
formats = Object.fromEntries(formats.map((format) => [format, true]));
|
|
|
|
|
|
2022-01-27 11:16:50 +08:00
|
|
|
return {
|
|
|
|
|
name: "visualizer",
|
|
|
|
|
setup(build) {
|
2022-01-27 16:53:07 +08:00
|
|
|
const { initialOptions: esbuildConfig, esbuild } = build;
|
2022-01-27 11:16:50 +08:00
|
|
|
esbuildConfig.metafile = true;
|
|
|
|
|
|
|
|
|
|
build.onEnd(async ({ metafile }) => {
|
|
|
|
|
const files = Object.keys(metafile.outputs);
|
|
|
|
|
|
|
|
|
|
if (files.length !== 1) {
|
|
|
|
|
throw new Error("Unexpected `outputs`.");
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-27 16:53:07 +08:00
|
|
|
if (formats.text || formats.stdout) {
|
2022-01-28 10:11:35 +08:00
|
|
|
const report = await esbuild.analyzeMetafile(metafile, {
|
|
|
|
|
verbose: true,
|
|
|
|
|
});
|
2022-01-27 11:16:50 +08:00
|
|
|
|
2022-01-27 16:53:07 +08:00
|
|
|
if (formats.stdout) {
|
|
|
|
|
console.log(report);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (formats.text) {
|
|
|
|
|
await fs.writeFile(`${esbuildConfig.outfile}.report.txt`, report);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (formats.html) {
|
2023-12-21 01:28:29 +08:00
|
|
|
const report = await esbuildVisualizer(metafile, {
|
2022-01-27 16:53:07 +08:00
|
|
|
title: files[0],
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await fs.writeFile(`${esbuildConfig.outfile}.report.html`, report);
|
|
|
|
|
}
|
2022-01-27 11:16:50 +08:00
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|