info.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { readdir, stat } from "fs";
  2. import type { Plugin } from "vite";
  3. import dayjs, { Dayjs } from "dayjs";
  4. import { sum } from "lodash-unified";
  5. import duration from "dayjs/plugin/duration";
  6. import { blue, bold, green } from "picocolors";
  7. dayjs.extend(duration);
  8. const staticPath = "dist";
  9. const fileListTotal: number[] = [];
  10. const recursiveDirectory = (folder: string, callback: Function): void => {
  11. readdir(folder, (err, files: string[]) => {
  12. if (err) throw err;
  13. let count = 0;
  14. const checkEnd = () => {
  15. ++count == files.length && callback();
  16. };
  17. files.forEach((item: string) => {
  18. stat(folder + "/" + item, async (err, stats) => {
  19. if (err) throw err;
  20. if (stats.isFile()) {
  21. fileListTotal.push(stats.size);
  22. checkEnd();
  23. } else if (stats.isDirectory()) {
  24. recursiveDirectory(`${staticPath}/${item}/`, checkEnd);
  25. }
  26. });
  27. });
  28. files.length === 0 && callback();
  29. });
  30. };
  31. const formatBytes = (a: number, b?: number): string => {
  32. if (0 == a) return "0 Bytes";
  33. const c = 1024,
  34. d = b || 2,
  35. e = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
  36. f = Math.floor(Math.log(a) / Math.log(c));
  37. return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
  38. };
  39. export function viteBuildInfo(): Plugin {
  40. let config: { command: string };
  41. let startTime: Dayjs;
  42. let endTime: Dayjs;
  43. return {
  44. name: "vite:buildInfo",
  45. configResolved(resolvedConfig: { command: string }) {
  46. config = resolvedConfig;
  47. },
  48. buildStart() {
  49. if (config.command === "build") {
  50. startTime = dayjs(new Date());
  51. }
  52. },
  53. closeBundle() {
  54. if (config.command === "build") {
  55. endTime = dayjs(new Date());
  56. recursiveDirectory(staticPath, () => {
  57. const spendTime = dayjs.duration(endTime.diff(startTime)).format("mm分ss秒");
  58. const packageSize = formatBytes(sum(fileListTotal));
  59. console.log(bold(green(`✨ ✨ ✨ Packaging is complete!!! ✨ ✨ ✨ `)));
  60. console.log(bold(blue(`Spend time: ${spendTime} package size:${packageSize}`)));
  61. });
  62. }
  63. }
  64. };
  65. }