forked from vercel/next.js
/
compiler.ts
64 lines (56 loc) · 1.84 KB
/
compiler.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
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { Span } from '../telemetry/trace'
export type CompilerResult = {
errors: string[]
warnings: string[]
}
function generateStats(
result: CompilerResult,
stat: webpack.Stats
): CompilerResult {
const { errors, warnings } = stat.toJson('errors-warnings')
if (errors.length > 0) {
result.errors.push(...errors)
}
if (warnings.length > 0) {
result.warnings.push(...warnings)
}
return result
}
// Webpack 5 requires the compiler to be closed (to save caches)
// Webpack 4 does not have this close method so in order to be backwards compatible we check if it exists
function closeCompiler(compiler: webpack.Compiler | webpack.MultiCompiler) {
return new Promise<void>((resolve, reject) => {
if ('close' in compiler) {
// @ts-ignore Close only exists on the compiler in webpack 5
return compiler.close((err: any) => (err ? reject(err) : resolve()))
}
resolve()
})
}
export function runCompiler(
config: webpack.Configuration,
{ runWebpackSpan }: { runWebpackSpan: Span }
): Promise<CompilerResult> {
return new Promise((resolve, reject) => {
const compiler = webpack(config)
compiler.run((err: Error, stats: webpack.Stats) => {
const webpackCloseSpan = runWebpackSpan.traceChild('webpack-close')
webpackCloseSpan
.traceAsyncFn(() => closeCompiler(compiler))
.then(() => {
if (err) {
const reason = err?.toString()
if (reason) {
return resolve({ errors: [reason], warnings: [] })
}
return reject(err)
}
const result = webpackCloseSpan
.traceChild('webpack-generate-error-stats')
.traceFn(() => generateStats({ errors: [], warnings: [] }, stats))
return resolve(result)
})
})
})
}