info.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. console.log(
  50. bold(
  51. green(
  52. `👏欢迎使用${blue(
  53. "[vue-pure-admin]"
  54. )},如果您感觉不错,记得点击后面链接给个star哦💖 https://github.com/xiaoxian521/vue-pure-admin`
  55. )
  56. )
  57. );
  58. if (config.command === "build") {
  59. startTime = dayjs(new Date());
  60. }
  61. },
  62. closeBundle() {
  63. if (config.command === "build") {
  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. }