rsnext/packages/next/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

import { readFileSync } from 'fs'
2020-05-13 17:43:41 +02:00
import * as path from 'path'
import { getBabelError } from './parseBabel'
2020-05-13 23:18:45 +02:00
import { getCssError } from './parseCss'
import { getScssError } from './parseScss'
import { getNotFoundError } from './parseNotFoundError'
2020-05-13 17:43:41 +02:00
import { SimpleWebpackError } from './simpleWebpackError'
import isError from '../../../../lib/is-error'
import type webpack5 from 'webpack5'
2020-05-13 17:43:41 +02:00
function getFileData(
compilation: webpack5.Compilation,
m: any
): [string, string | null] {
let resolved: string
let ctx: string | null = compilation.compiler?.context ?? null
2020-05-13 23:18:45 +02:00
if (ctx !== null && typeof m.resource === 'string') {
const res = path.relative(ctx, m.resource).replace(/\\/g, path.posix.sep)
resolved = res.startsWith('.') ? res : `.${path.posix.sep}${res}`
} else {
const requestShortener = compilation.requestShortener
if (typeof m?.readableIdentifier === 'function') {
resolved = m.readableIdentifier(requestShortener)
} else {
resolved = m.request ?? m.userRequest
}
2020-05-13 23:18:45 +02:00
}
if (resolved) {
let content: string | null = null
try {
content = readFileSync(
ctx ? path.resolve(ctx, resolved) : resolved,
'utf8'
)
} catch {}
return [resolved, content]
2020-05-13 17:43:41 +02:00
}
return ['<unknown>', null]
2020-05-13 17:43:41 +02:00
}
export async function getModuleBuildError(
compilation: webpack5.Compilation,
2020-05-13 17:43:41 +02:00
input: any
): Promise<SimpleWebpackError | false> {
2020-05-13 17:43:41 +02:00
if (
!(
typeof input === 'object' &&
(input?.name === 'ModuleBuildError' ||
input?.name === 'ModuleNotFoundError') &&
2020-05-13 17:43:41 +02:00
Boolean(input.module) &&
isError(input.error)
2020-05-13 17:43:41 +02:00
)
) {
return false
}
const err: Error = input.error
const [sourceFilename, sourceContent] = getFileData(compilation, input.module)
2020-05-13 23:18:45 +02:00
const notFoundError = await getNotFoundError(
compilation,
input,
sourceFilename
)
if (notFoundError !== false) {
return notFoundError
}
2020-05-13 17:43:41 +02:00
const babel = getBabelError(sourceFilename, err)
if (babel !== false) {
return babel
}
2020-05-13 23:18:45 +02:00
const css = getCssError(sourceFilename, err)
if (css !== false) {
return css
}
const scss = getScssError(sourceFilename, sourceContent, err)
if (scss !== false) {
return scss
}
2020-05-13 17:43:41 +02:00
return false
}