formatStats.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. module.exports = function formatStats (stats, dir, api) {
  2. const fs = require('fs')
  3. const path = require('path')
  4. const zlib = require('zlib')
  5. const ui = require('cliui')({ width: process.stdout.columns || 80 })
  6. const { chalk } = require('@vue/cli-shared-utils')
  7. const json = stats.toJson({
  8. hash: false,
  9. modules: false,
  10. chunks: false
  11. })
  12. let assets = json.assets
  13. ? json.assets
  14. : json.children.reduce((acc, child) => acc.concat(child.assets), [])
  15. const seenNames = new Map()
  16. const isJS = val => /\.js$/.test(val)
  17. const isCSS = val => /\.css$/.test(val)
  18. const isMinJS = val => /\.min\.js$/.test(val)
  19. assets = assets
  20. .map(a => {
  21. a.name = a.name.split('?')[0]
  22. return a
  23. })
  24. .filter(a => {
  25. if (seenNames.has(a.name)) {
  26. return false
  27. }
  28. seenNames.set(a.name, true)
  29. return isJS(a.name) || isCSS(a.name)
  30. })
  31. .sort((a, b) => {
  32. if (isJS(a.name) && isCSS(b.name)) return -1
  33. if (isCSS(a.name) && isJS(b.name)) return 1
  34. if (isMinJS(a.name) && !isMinJS(b.name)) return -1
  35. if (!isMinJS(a.name) && isMinJS(b.name)) return 1
  36. return b.size - a.size
  37. })
  38. function formatSize (size) {
  39. return (size / 1024).toFixed(2) + ' KiB'
  40. }
  41. function getGzippedSize (asset) {
  42. const filepath = api.resolve(path.join(dir, asset.name))
  43. const buffer = fs.readFileSync(filepath)
  44. return formatSize(zlib.gzipSync(buffer).length)
  45. }
  46. function makeRow (a, b, c) {
  47. return ` ${a}\t ${b}\t ${c}`
  48. }
  49. ui.div(
  50. makeRow(
  51. chalk.cyan.bold(`File`),
  52. chalk.cyan.bold(`Size`),
  53. chalk.cyan.bold(`Gzipped`)
  54. ) + `\n\n` +
  55. assets.map(asset => makeRow(
  56. /js$/.test(asset.name)
  57. ? chalk.green(path.join(dir, asset.name))
  58. : chalk.blue(path.join(dir, asset.name)),
  59. formatSize(asset.size),
  60. getGzippedSize(asset)
  61. )).join(`\n`)
  62. )
  63. return `${ui.toString()}\n\n ${chalk.gray(`Images and other types of assets omitted.`)}\n`
  64. }