formatStats.js 1.9 KB

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