diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 7a4a55a12348d1..aafa1a16bdbd37 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -1,7 +1,12 @@ import path from 'path' import type { Plugin } from '../plugin' import type { ViteDevServer } from '../server' -import type { OutputAsset, OutputBundle, OutputChunk } from 'rollup' +import type { + OutputAsset, + OutputBundle, + OutputChunk, + RollupError +} from 'rollup' import { cleanUrl, generateCodeFrame, @@ -24,7 +29,8 @@ import { modulePreloadPolyfillId } from './modulePreloadPolyfill' import type { AttributeNode, NodeTransform, - ElementNode + ElementNode, + CompilerError } from '@vue/compiler-dom' import { NodeTypes } from '@vue/compiler-dom' @@ -114,14 +120,7 @@ export async function traverseHtml( nodeTransforms: [visitor] }) } catch (e) { - const parseError = { - loc: filePath, - frame: '', - ...formatParseError(e, filePath, html) - } - throw new Error( - `Unable to parse ${JSON.stringify(parseError.loc)}\n${parseError.frame}` - ) + handleParseError(e, html, filePath) } } @@ -148,17 +147,44 @@ export function getScriptInfo(node: ElementNode): { return { src, isModule, isAsync } } -function formatParseError(e: any, id: string, html: string): Error { - // normalize the error to rollup format - if (e.loc) { - e.frame = generateCodeFrame(html, e.loc.start.offset) - e.loc = { +/** + * Format Vue @type {CompilerError} to @type {RollupError} + */ +function formatParseError( + compilerError: CompilerError, + id: string, + html: string +): RollupError { + const formattedError: RollupError = { ...(compilerError as any) } + if (compilerError.loc) { + formattedError.frame = generateCodeFrame( + html, + compilerError.loc.start.offset + ) + formattedError.loc = { file: id, - line: e.loc.start.line, - column: e.loc.start.column + line: compilerError.loc.start.line, + column: compilerError.loc.start.column } } - return e + return formattedError +} + +function handleParseError( + compilerError: CompilerError, + html: string, + filePath: string +) { + const parseError = { + loc: filePath, + frame: '', + ...formatParseError(compilerError, filePath, html) + } + throw new Error( + `Unable to parse HTML; ${compilerError.message}\n at ${JSON.stringify( + parseError.loc + )}\n${parseError.frame}` + ) } /**