/
measureWebpackPerformance.ts
63 lines (52 loc) · 2.12 KB
/
measureWebpackPerformance.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
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-console */
import path from 'path'
import fs from 'fs'
import chalk from 'chalk'
import SpeedMeasurePlugin from 'speed-measure-webpack-plugin'
import type { Configuration } from 'webpack'
/**
* @internal
*/
export function measureWebpackPerformance (webpackConfig: Configuration) {
if (!process.env.WEBPACK_PERF_MEASURE) {
throw new Error('Performance monitoring is possible only with WEBPACK_PERF_MEASURE env variable set')
}
const compareWithPrevious = process.env.WEBPACK_PERF_MEASURE_COMPARE
function percentageDiff (a: number, b: number) {
return ((a - b) / a) * 100
}
const compareOutput = (output: string) => {
const statsPath = path.resolve(__dirname, '..', '__perf-stats', `${compareWithPrevious}.json`)
if (!fs.existsSync(statsPath) || process.env.WEBPACK_PERF_MEASURE_UPDATE) {
return fs.writeFileSync(statsPath, output, { encoding: 'utf-8' })
}
const newStats = JSON.parse(output)
const oldStats = require(statsPath)
const totalPercentageDiff = percentageDiff(oldStats.misc.compileTime, newStats.misc.compileTime)
const printResult = (result: string) => {
const delimiter = new Array(process.stdout.columns).fill('═').join('')
console.log(delimiter)
console.log(`${chalk.bold('WEBPACK_PERF_MEASURE')}`)
console.log(`Before: ${chalk.bold(oldStats.misc.compileTime / 1000)}s`)
console.log(`After: ${chalk.bold(newStats.misc.compileTime / 1000)}s`)
console.log(result)
console.log(delimiter)
}
if (Math.abs(totalPercentageDiff) < 5) {
printResult('No sufficient build time difference')
} else if (totalPercentageDiff > 0) {
printResult(`New build is faster: ${chalk.green.bold(`+${Math.round(totalPercentageDiff)}%`)}`)
} else {
printResult(`New build is slower: ${chalk.red.bold(`${Math.round(totalPercentageDiff)}%`)}`)
}
}
const smp = compareWithPrevious ?
new SpeedMeasurePlugin({
outputFormat: 'json',
outputTarget: compareOutput,
})
: new SpeedMeasurePlugin()
// @ts-expect-error
return smp.wrap(webpackConfig)
}