2021-01-14 02:59:08 +01:00
|
|
|
import { webpack } from 'next/dist/compiled/webpack/webpack'
|
2018-12-03 14:18:52 +01:00
|
|
|
|
2018-12-11 21:46:23 +01:00
|
|
|
export type CompilerResult = {
|
2020-04-06 17:58:35 +02:00
|
|
|
errors: string[]
|
|
|
|
warnings: string[]
|
2018-12-03 14:18:52 +01:00
|
|
|
}
|
|
|
|
|
2021-01-14 02:59:08 +01:00
|
|
|
function generateStats(
|
|
|
|
result: CompilerResult,
|
|
|
|
stat: webpack.Stats
|
|
|
|
): CompilerResult {
|
2020-04-06 17:58:35 +02:00
|
|
|
const { errors, warnings } = stat.toJson('errors-warnings')
|
2019-03-10 15:46:50 +01:00
|
|
|
if (errors.length > 0) {
|
2020-04-06 17:58:35 +02:00
|
|
|
result.errors.push(...errors)
|
2019-03-10 15:46:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (warnings.length > 0) {
|
2020-04-06 17:58:35 +02:00
|
|
|
result.warnings.push(...warnings)
|
2019-03-10 15:46:50 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2020-06-17 17:00:29 +02:00
|
|
|
// 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((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()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-02-17 12:56:48 +01:00
|
|
|
export function runCompiler(
|
2021-01-14 02:59:08 +01:00
|
|
|
config: webpack.Configuration | webpack.Configuration[]
|
2019-02-17 12:56:48 +01:00
|
|
|
): Promise<CompilerResult> {
|
2020-06-17 17:00:29 +02:00
|
|
|
return new Promise((resolve, reject) => {
|
2018-12-03 14:18:52 +01:00
|
|
|
const compiler = webpack(config)
|
2020-04-06 17:58:35 +02:00
|
|
|
compiler.run(
|
2021-01-14 02:59:08 +01:00
|
|
|
(
|
|
|
|
err: Error,
|
|
|
|
statsOrMultiStats: { stats: webpack.Stats[] } | webpack.Stats
|
|
|
|
) => {
|
2020-06-17 17:00:29 +02:00
|
|
|
closeCompiler(compiler).then(() => {
|
|
|
|
if (err) {
|
|
|
|
const reason = err?.toString()
|
|
|
|
if (reason) {
|
|
|
|
return resolve({ errors: [reason], warnings: [] })
|
|
|
|
}
|
|
|
|
return reject(err)
|
2020-05-29 00:51:30 +02:00
|
|
|
}
|
2018-12-03 14:18:52 +01:00
|
|
|
|
2020-06-17 17:00:29 +02:00
|
|
|
if ('stats' in statsOrMultiStats) {
|
|
|
|
const result: CompilerResult = statsOrMultiStats.stats.reduce(
|
|
|
|
generateStats,
|
|
|
|
{ errors: [], warnings: [] }
|
|
|
|
)
|
|
|
|
return resolve(result)
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = generateStats(
|
|
|
|
{ errors: [], warnings: [] },
|
|
|
|
statsOrMultiStats
|
2020-04-06 17:58:35 +02:00
|
|
|
)
|
|
|
|
return resolve(result)
|
2020-06-17 17:00:29 +02:00
|
|
|
})
|
2019-03-10 15:46:50 +01:00
|
|
|
}
|
2020-04-06 17:58:35 +02:00
|
|
|
)
|
2018-12-03 14:18:52 +01:00
|
|
|
})
|
|
|
|
}
|