12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- import { readdir, stat } from "fs";
- import type { Plugin } from "vite";
- import dayjs, { Dayjs } from "dayjs";
- import { sum } from "lodash-unified";
- import duration from "dayjs/plugin/duration";
- import { blue, bold, green } from "picocolors";
- 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, async (err, stats) => {
- if (err) throw err;
- if (stats.isFile()) {
- fileListTotal.push(stats.size);
- checkEnd();
- } else if (stats.isDirectory()) {
- recursiveDirectory(`${staticPath}/${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") {
- endTime = dayjs(new Date());
- recursiveDirectory(staticPath, () => {
- const spendTime = dayjs.duration(endTime.diff(startTime)).format("mm分ss秒");
- const packageSize = formatBytes(sum(fileListTotal));
- console.log(bold(green(`✨ ✨ ✨ Packaging is complete!!! ✨ ✨ ✨ `)));
- console.log(bold(blue(`Spend time: ${spendTime} package size:${packageSize}`)));
- });
- }
- }
- };
- }
|