You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.4 KiB

  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 { green, blue, bold } 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. console.log(
  56. bold(
  57. green(
  58. `👏欢迎使用${blue(
  59. "[vue-pure-admin]"
  60. )}star哦💖 https://github.com/xiaoxian521/vue-pure-admin`
  61. )
  62. )
  63. );
  64. endTime = dayjs(new Date());
  65. recursiveDirectory(staticPath, () => {
  66. console.log(
  67. bold(
  68. green(
  69. `恭喜打包完成🎉(总用时${dayjs
  70. .duration(endTime.diff(startTime))
  71. .format("mm分ss秒")}${formatBytes(
  72. sum(fileListTotal)
  73. )}`
  74. )
  75. )
  76. );
  77. });
  78. }
  79. }
  80. };
  81. }