/* * @Author: wei.li * @Date: 2022-03-07 11:37:59 * @LastEditors: levi7754 levi7754@163.com * @LastEditTime: 2024-07-03 17:08:08 * @Description: file content */ import { readdir, stat } from 'fs'; import dayjs, { type Dayjs } from 'dayjs'; import xutils from 'xe-utils'; import duration from 'dayjs/plugin/duration'; import gradientString from 'gradient-string'; import boxen from 'boxen'; dayjs.extend(duration); const boxenOprions: any = { padding: 0.5, borderColor: 'cyan', borderStyle: 'round' }; 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, async (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() { let config: { command: string }; let startTime: Dayjs; let endTime: Dayjs; let totalTime: string; return { name: 'vite:buildInfo', configResolved(resolvedConfig: { command: string }) { config = resolvedConfig; }, buildStart() { if (config.command === 'build') { startTime = dayjs(new Date()); } }, closeBundle() { if (config.command === 'build') { endTime = dayjs(new Date()); totalTime = dayjs.duration(endTime.diff(startTime)).format('mm分ss秒'); recursiveDirectory(staticPath, () => { console.log( boxen( gradientString('cyan', 'magenta').multiline( `🎉 恭喜打包完成(总用时${totalTime},打包后的大小为${formatBytes(xutils.sum(fileListTotal))})` ), boxenOprions ) ); }); } } }; }