/
reporter.ts
245 lines (223 loc) · 6.57 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
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 { normalizePath } from '../utils'
import { LogLevels } from '../logger'
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: colors.cyan,
[WriteType.CSS]: colors.magenta,
[WriteType.ASSET]: colors.green,
[WriteType.HTML]: colors.blue,
[WriteType.SOURCE_MAP]: colors.gray
}
export function buildReporterPlugin(config: ResolvedConfig): Plugin {
const compress = promisify(gzip)
const chunkLimit = config.build.chunkSizeWarningLimit
function isLarge(code: string | Uint8Array): boolean {
// bail out on particularly large chunks
return code.length / 1024 > chunkLimit
}
async function getCompressedSize(code: string | Uint8Array): Promise<string> {
if (config.build.ssr || !config.build.reportCompressedSize) {
return ''
}
return ` / gzip: ${(
(await compress(typeof code === 'string' ? code : Buffer.from(code)))
.length / 1024
).toFixed(2)} KiB`
}
function printFileInfo(
filePath: string,
content: string | Uint8Array,
type: WriteType,
maxLength: number,
compressedSize = ''
) {
const outDir =
normalizePath(
path.relative(
config.root,
path.resolve(config.root, config.build.outDir)
)
) + '/'
const kibs = content.length / 1024
const sizeColor = kibs > chunkLimit ? colors.yellow : colors.dim
config.logger.info(
`${colors.gray(colors.white(colors.dim(outDir)))}${writeColors[type](
filePath.padEnd(maxLength + 2)
)} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`
)
}
const tty = process.stdout.isTTY && !process.env.CI
const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info
let hasTransformed = false
let hasRenderedChunk = false
let transformedCount = 0
let chunkCount = 0
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
},
buildEnd() {
if (shouldLogInfo) {
if (tty) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
config.logger.info(
`${colors.green(`✓`)} ${transformedCount} modules transformed.`
)
}
},
renderStart() {
chunkCount = 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) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
}
},
async writeBundle(_, output) {
let hasLargeChunks = false
if (shouldLogInfo) {
let longest = 0
for (const file in output) {
const l = output[file].fileName.length
if (l > longest) longest = l
}
// large chunks are deferred to be logged at the end so they are more
// visible.
const deferredLogs: (() => void)[] = []
await Promise.all(
Object.keys(output).map(async (file) => {
const chunk = output[file]
if (chunk.type === 'chunk') {
const log = async () => {
printFileInfo(
chunk.fileName,
chunk.code,
WriteType.JS,
longest,
await getCompressedSize(chunk.code)
)
if (chunk.map) {
printFileInfo(
chunk.fileName + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP,
longest
)
}
}
if (isLarge(chunk.code)) {
hasLargeChunks = true
deferredLogs.push(log)
} else {
await log()
}
} else if (chunk.source) {
const isCSS = chunk.fileName.endsWith('.css')
const isMap = chunk.fileName.endsWith('.js.map')
printFileInfo(
chunk.fileName,
chunk.source,
isCSS
? WriteType.CSS
: isMap
? WriteType.SOURCE_MAP
: WriteType.ASSET,
longest,
isCSS ? await getCompressedSize(chunk.source) : undefined
)
}
})
)
await Promise.all(deferredLogs.map((l) => l()))
} else {
hasLargeChunks = Object.keys(output).some((file) => {
const chunk = output[file]
return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit
})
}
if (
hasLargeChunks &&
config.build.minify &&
!config.build.lib &&
!config.build.ssr
) {
config.logger.warn(
colors.yellow(
`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` +
`- Using dynamic import() to code-split the application\n` +
`- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` +
`- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`
)
)
}
}
}
}
function writeLine(output: string) {
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
if (output.length < process.stdout.columns) {
process.stdout.write(output)
} else {
process.stdout.write(output.substring(0, process.stdout.columns - 1))
}
}
function throttle(fn: Function) {
let timerHandle: NodeJS.Timeout | null = null
return (...args: any[]) => {
if (timerHandle) return
fn(...args)
timerHandle = setTimeout(() => {
timerHandle = null
}, 100)
}
}