vite-build-info.ts 2.4 KB

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