-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
reporter.ts
318 lines (288 loc) · 9.05 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import path from 'node:path'
import { gzip } from 'node:zlib'
import { promisify } from 'node:util'
import colors from 'picocolors'
import type { Plugin } from 'rollup'
import type { ResolvedConfig } from '../config'
import { isDefined, normalizePath } from '../utils'
import { LogLevels } from '../logger'
const groups = [
{ name: 'Assets', color: colors.green },
{ name: 'CSS', color: colors.magenta },
{ name: 'JS', color: colors.cyan },
]
type LogEntry = {
name: string
group: (typeof groups)[number]['name']
size: number
compressedSize: number | null
mapSize: number | null
}
const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/
export function buildReporterPlugin(config: ResolvedConfig): Plugin {
const compress = promisify(gzip)
const chunkLimit = config.build.chunkSizeWarningLimit
const tty = process.stdout.isTTY && !process.env.CI
const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info
let hasTransformed = false
let hasRenderedChunk = false
let hasCompressChunk = false
let transformedCount = 0
let chunkCount = 0
let compressedCount = 0
let startTime = Date.now()
async function getCompressedSize(
code: string | Uint8Array,
): Promise<number | null> {
if (config.build.ssr || !config.build.reportCompressedSize) {
return null
}
if (shouldLogInfo && !hasCompressChunk) {
if (!tty) {
config.logger.info('computing gzip size...')
} else {
writeLine('computing gzip size (0)...')
}
hasCompressChunk = true
}
const compressed = await compress(
typeof code === 'string' ? code : Buffer.from(code),
)
compressedCount++
if (shouldLogInfo && tty) {
writeLine(`computing gzip size (${compressedCount})...`)
}
return compressed.length
}
const logTransform = throttle((id: string) => {
writeLine(
`transforming (${transformedCount}) ${colors.dim(
path.relative(config.root, id),
)}`,
)
})
return {
name: 'vite:reporter',
transform(_, id) {
transformedCount++
if (shouldLogInfo) {
if (!tty) {
if (!hasTransformed) {
config.logger.info(`transforming...`)
}
} else {
if (id.includes(`?`)) return
logTransform(id)
}
hasTransformed = true
}
return null
},
options() {
startTime = Date.now()
},
buildEnd() {
if (shouldLogInfo) {
if (tty) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
config.logger.info(
`${colors.green(`✓`)} ${transformedCount} modules transformed.`,
)
}
},
renderStart() {
chunkCount = 0
compressedCount = 0
},
renderChunk() {
chunkCount++
if (shouldLogInfo) {
if (!tty) {
if (!hasRenderedChunk) {
config.logger.info('rendering chunks...')
}
} else {
writeLine(`rendering chunks (${chunkCount})...`)
}
hasRenderedChunk = true
}
return null
},
generateBundle() {
if (shouldLogInfo && tty) clearLine()
},
async writeBundle({ dir: outDir }, output) {
let hasLargeChunks = false
if (shouldLogInfo) {
const entries = (
await Promise.all(
Object.values(output).map(
async (chunk): Promise<LogEntry | null> => {
if (chunk.type === 'chunk') {
return {
name: chunk.fileName,
group: 'JS',
size: chunk.code.length,
compressedSize: await getCompressedSize(chunk.code),
mapSize: chunk.map ? chunk.map.toString().length : null,
}
} else {
if (chunk.fileName.endsWith('.map')) return null
const isCSS = chunk.fileName.endsWith('.css')
const isCompressible =
isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName)
return {
name: chunk.fileName,
group: isCSS ? 'CSS' : 'Assets',
size: chunk.source.length,
mapSize: null, // Rollup doesn't support CSS maps?
compressedSize: isCompressible
? await getCompressedSize(chunk.source)
: null,
}
}
},
),
)
).filter(isDefined)
if (tty) clearLine()
let longest = 0
let biggestSize = 0
let biggestMap = 0
let biggestCompressSize = 0
for (const entry of entries) {
if (entry.name.length > longest) longest = entry.name.length
if (entry.size > biggestSize) biggestSize = entry.size
if (entry.mapSize && entry.mapSize > biggestMap) {
biggestMap = entry.mapSize
}
if (
entry.compressedSize &&
entry.compressedSize > biggestCompressSize
) {
biggestCompressSize = entry.compressedSize
}
}
const sizePad = displaySize(biggestSize).length
const mapPad = displaySize(biggestMap).length
const compressPad = displaySize(biggestCompressSize).length
const relativeOutDir = normalizePath(
path.relative(
config.root,
path.resolve(config.root, outDir ?? config.build.outDir),
),
)
const assetsDir = path.join(config.build.assetsDir, '/')
for (const group of groups) {
const filtered = entries.filter((e) => e.group === group.name)
if (!filtered.length) continue
for (const entry of filtered.sort((a, z) => a.size - z.size)) {
const isLarge =
group.name === 'JS' && entry.size / 1000 > chunkLimit
if (isLarge) hasLargeChunks = true
const sizeColor = isLarge ? colors.yellow : colors.dim
let log = colors.dim(relativeOutDir + '/')
log +=
!config.build.lib && entry.name.startsWith(assetsDir)
? colors.dim(assetsDir) +
group.color(
entry.name
.slice(assetsDir.length)
.padEnd(longest + 2 - assetsDir.length),
)
: group.color(entry.name.padEnd(longest + 2))
log += colors.bold(
sizeColor(displaySize(entry.size).padStart(sizePad)),
)
if (entry.compressedSize) {
log += colors.dim(
` │ gzip: ${displaySize(entry.compressedSize).padStart(
compressPad,
)}`,
)
}
if (entry.mapSize) {
log += colors.dim(
` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`,
)
}
config.logger.info(log)
}
}
} else {
hasLargeChunks = Object.values(output).some((chunk) => {
return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit
})
}
if (
hasLargeChunks &&
config.build.minify &&
!config.build.lib &&
!config.build.ssr
) {
config.logger.warn(
colors.yellow(
`\n(!) Some chunks are larger than ${chunkLimit} kBs after minification. Consider:\n` +
`- Using dynamic import() to code-split the application\n` +
`- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` +
`- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`,
),
)
}
},
closeBundle() {
if (shouldLogInfo && !config.build.watch) {
config.logger.info(
`${colors.green(`✓`)} built in ${displayTime(
Date.now() - startTime,
)}`,
)
}
},
}
}
function writeLine(output: string) {
clearLine()
if (output.length < process.stdout.columns) {
process.stdout.write(output)
} else {
process.stdout.write(output.substring(0, process.stdout.columns - 1))
}
}
function clearLine() {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
function throttle(fn: Function) {
let timerHandle: NodeJS.Timeout | null = null
return (...args: any[]) => {
if (timerHandle) return
fn(...args)
timerHandle = setTimeout(() => {
timerHandle = null
}, 100)
}
}
function displaySize(bytes: number) {
return `${(bytes / 1000).toLocaleString('en', {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})} kB`
}
function displayTime(time: number) {
// display: {X}ms
if (time < 1000) {
return `${time}ms`
}
time = time / 1000
// display: {X}s
if (time < 60) {
return `${time.toFixed(2)}s`
}
const mins = parseInt((time / 60).toString())
const seconds = time % 60
// display: {X}m {Y}s
return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`
}