buildInfo.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import boxen from 'boxen';
  2. import dayjs from 'dayjs';
  3. import duration from 'dayjs/plugin/duration';
  4. import gradient from 'gradient-string';
  5. import { getPackageSize } from './utils';
  6. import type { Options as BoxenOptions } from 'boxen';
  7. import type { Dayjs } from 'dayjs';
  8. import type { Plugin } from 'vite';
  9. dayjs.extend(duration);
  10. const welcomeMessage = gradient(['cyan', 'magenta']).multiline(`正在打包...`);
  11. const boxenOptions: BoxenOptions = {
  12. padding: 0.5,
  13. borderColor: 'cyan',
  14. borderStyle: 'round',
  15. };
  16. export function viteBuildInfo(): Plugin {
  17. let config: { command: string };
  18. let startTime: Dayjs;
  19. let endTime: Dayjs;
  20. let outDir: string;
  21. return {
  22. name: 'vite:buildInfo',
  23. configResolved(resolvedConfig) {
  24. config = resolvedConfig;
  25. outDir = resolvedConfig.build?.outDir ?? 'dist';
  26. },
  27. buildStart() {
  28. if (config.command === 'build') {
  29. console.log('\n' + boxen(welcomeMessage, boxenOptions));
  30. startTime = dayjs(new Date());
  31. }
  32. },
  33. closeBundle() {
  34. if (config.command === 'build') {
  35. endTime = dayjs(new Date());
  36. getPackageSize({
  37. folder: outDir,
  38. callback: (size: string | number) => {
  39. console.log(
  40. '\n' +
  41. boxen(
  42. gradient(['cyan', 'magenta']).multiline(
  43. `🎉 恭喜打包完成\n` +
  44. `总用时:${dayjs.duration(endTime.diff(startTime)).format('mm分ss秒')}\n` +
  45. `打包后的大小为:${size}`
  46. ),
  47. boxenOptions
  48. )
  49. );
  50. },
  51. });
  52. }
  53. },
  54. };
  55. }