formatStats.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 chalk = require('chalk')
  6. const ui = require('cliui')({ width: 80 })
  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. .filter(a => {
  21. if (seenNames.has(a.name)) {
  22. return false
  23. }
  24. seenNames.set(a.name, true)
  25. return isJS(a.name) || isCSS(a.name)
  26. })
  27. .sort((a, b) => {
  28. if (isJS(a.name) && isCSS(b.name)) return -1
  29. if (isCSS(a.name) && isJS(b.name)) return 1
  30. if (isMinJS(a.name) && !isMinJS(b.name)) return -1
  31. if (!isMinJS(a.name) && isMinJS(b.name)) return 1
  32. return b.size - a.size
  33. })
  34. function formatSize (size) {
  35. return (size / 1024).toFixed(2) + ' KiB'
  36. }
  37. function getGzippedSize (asset) {
  38. const filepath = api.resolve(path.join(dir, asset.name))
  39. const buffer = fs.readFileSync(filepath)
  40. return formatSize(zlib.gzipSync(buffer).length)
  41. }
  42. function makeRow (a, b, c) {
  43. return ` ${a}\t ${b}\t ${c}`
  44. }
  45. ui.div(
  46. makeRow(
  47. chalk.cyan.bold(`File`),
  48. chalk.cyan.bold(`Size`),
  49. chalk.cyan.bold(`Gzipped`)
  50. ) + `\n\n` +
  51. assets.map(asset => makeRow(
  52. /js$/.test(asset.name)
  53. ? chalk.green(path.join(dir, asset.name))
  54. : chalk.blue(path.join(dir, asset.name)),
  55. formatSize(asset.size),
  56. getGzippedSize(asset)
  57. )).join(`\n`)
  58. )
  59. return `${ui.toString()}\n\n ${chalk.gray(`Images and other types of assets omitted.`)}\n`
  60. }