/
reporter.ts
88 lines (81 loc) · 2.21 KB
/
reporter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import path from 'path'
import chalk from 'chalk'
import { Plugin } from 'rollup'
import { ResolvedConfig } from '../config'
import { sync as brotliSizeSync } from 'brotli-size'
import { normalizePath } from '../utils'
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
export function buildReporterPlugin(config: ResolvedConfig): Plugin {
function printFileInfo(
filePath: string,
content: string | Uint8Array,
type: WriteType,
maxLength: number
) {
const needCompression =
type === WriteType.JS || type === WriteType.CSS || type === WriteType.HTML
const compressed = needCompression
? ` / brotli: ${(
brotliSizeSync(
typeof content === 'string' ? content : Buffer.from(content)
) / 1024
).toFixed(2)}kb`
: ``
const outDir =
normalizePath(
path.relative(
config.root,
path.resolve(config.root, config.build.outDir)
)
) + '/'
config.logger.info(
`${chalk.gray(chalk.white.dim(outDir))}${writeColors[type](
filePath.padEnd(maxLength + 2)
)} ${chalk.dim(`${(content.length / 1024).toFixed(2)}kb${compressed}`)}`
)
}
return {
name: 'vite:size',
writeBundle(_, output) {
let longest = 0
for (const file in output) {
const l = output[file].fileName.length
if (l > longest) longest = l
}
for (const file in output) {
const chunk = output[file]
if (chunk.type === 'chunk') {
printFileInfo(chunk.fileName, chunk.code, WriteType.JS, longest)
if (chunk.map) {
printFileInfo(
chunk.fileName + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP,
longest
)
}
} else if (chunk.source) {
printFileInfo(
chunk.fileName,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET,
longest
)
}
}
}
}
}