wupengfei
2025-02-20 d924a0e3ad6d0d9905e5c198d64dc3339f3bc549
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { readdir, stat } from 'fs';
import type { Plugin } from 'vite';
 
import { sum } from 'lodash';
 
import picocolors from 'picocolors';
const { green, blue, bold } = picocolors;
 
import dayjs, { Dayjs } from 'dayjs';
import duration from 'dayjs/plugin/duration.js';
import pkg from '../package.json';
 
dayjs.extend(duration);
 
const staticPath = 'dist';
const fileListTotal: number[] = [];
 
const recursiveDirectory = (folder: string, callback: Function): void => {
  readdir(folder, (err, files: string[]) => {
    if (err) throw err;
    let count = 0;
    const checkEnd = () => {
      ++count === files.length && callback();
    };
    files.forEach((item: string) => {
      stat(folder + '/' + item, (err, stats) => {
        if (err) throw err;
        if (stats.isFile()) {
          fileListTotal.push(stats.size);
          checkEnd();
        } else if (stats.isDirectory()) {
          recursiveDirectory(`${folder}/${item}/`, checkEnd);
        }
      });
    });
    files.length === 0 && callback();
  });
};
 
const formatBytes = (a: number, b?: number): string => {
  if (0 === a) return '0 Bytes';
  const c = 1024,
    d = b || 2,
    e = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    f = Math.floor(Math.log(a) / Math.log(c));
  return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f];
};
 
export function viteBuildInfo(): Plugin {
  let config: { command: string };
  let startTime: Dayjs;
  let endTime: Dayjs;
 
  return {
    name: 'vite:buildInfo',
    configResolved(resolvedConfig: { command: string }) {
      config = resolvedConfig;
    },
    buildStart() {
      if (config.command === 'build') {
        startTime = dayjs(new Date());
      }
    },
    closeBundle() {
      if (config.command === 'build') {
        console.log(bold(green(`👏欢迎使用${blue(pkg.name)}`)));
        endTime = dayjs(new Date());
        recursiveDirectory(staticPath, () => {
          console.log(
            bold(
              green(
                `恭喜打包完成🎉(总用时${dayjs
                  .duration(endTime.diff(startTime))
                  .format('mm分ss秒')},打包后的大小为${formatBytes(
                  sum(fileListTotal)
                )}); 请确认.env文件的 VITE_PROXY_DOMAIN_REAL和VITE_OSS_URL`
              )
            )
          );
        });
      }
    },
  };
}