UNPKG

2.27 kBJavaScriptView Raw
1/* eslint-disable */
2/**
3 * @see https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-service/lib/commands/build/formatStats.js
4 */
5module.exports = function formatStats (stats, dir) {
6 const fs = require('fs')
7 const path = require('path')
8 const zlib = require('zlib')
9 const chalk = require('chalk')
10 const ui = require('cliui')({ width: 80 })
11
12 const json = stats.toJson({
13 hash: false,
14 modules: false,
15 chunks: false
16 })
17
18 let assets = json.assets
19 ? json.assets
20 : json.children.reduce((acc, child) => acc.concat(child.assets), [])
21
22 const seenNames = new Map()
23 const isJS = val => /\.js$/.test(val)
24 const isCSS = val => /\.css$/.test(val)
25 const isMinJS = val => /\.min\.js$/.test(val)
26 assets = assets
27 .filter(a => {
28 if (seenNames.has(a.name)) {
29 return false
30 }
31 seenNames.set(a.name, true)
32 return isJS(a.name) || isCSS(a.name)
33 })
34 .sort((a, b) => {
35 if (isJS(a.name) && isCSS(b.name)) return -1
36 if (isCSS(a.name) && isJS(b.name)) return 1
37 if (isMinJS(a.name) && !isMinJS(b.name)) return -1
38 if (!isMinJS(a.name) && isMinJS(b.name)) return 1
39 return b.size - a.size
40 })
41
42 function formatSize (size) {
43 if (size >= 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
44 return (size / 1024).toFixed(2) + ' KB'
45 }
46
47 function getGzippedSize (asset) {
48 const filepath = path.join(dir, asset.name)
49 const buffer = fs.readFileSync(filepath)
50 return zlib.gzipSync(buffer).length;
51 }
52
53 function makeRow (a, b, c, bold) {
54 return ` ${a}\t ${b}\t ${c}`;
55 }
56
57 function getRow(ast) {
58 const maxSize = 50 * 1024;
59 let row = [];
60 if (/js$/.test(ast.name)) {
61 row.push(chalk.green(ast.name));
62 }
63 else {
64 row.push(chalk.blue(ast.name));
65 }
66
67 row.push(formatSize(ast.size));
68 const gzipSize = getGzippedSize(ast);
69 row.push(formatSize(gzipSize));
70
71 if (gzipSize >= maxSize) {
72 row[0] = chalk.bold(row[0]);
73 row[1] = chalk.yellow(chalk.bold(row[1]));
74 row[2] = chalk.yellow(chalk.bold(row[2]));
75 }
76
77 return makeRow(...row);
78 }
79
80 ui.div(
81 makeRow(
82 chalk.cyan.bold(`File`),
83 chalk.cyan.bold(`Size`),
84 chalk.cyan.bold(`Gzipped`)
85 ) + `\n\n` +
86 assets.map(getRow).join(`\n`)
87 )
88
89 return `${ui.toString()}\n\n ${chalk.gray(`Images and other types of assets omitted.`)}\n`
90 }