Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 13 additions & 21 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,21 +228,17 @@ export function overwriteAttrValue(
/**
* Format parse5 @type {ParserError} to @type {RollupError}
*/
function formatParseError(
parserError: ParserError,
id: string,
html: string,
): RollupError {
const formattedError: RollupError = {
function formatParseError(parserError: ParserError, id: string, html: string) {
const formattedError = {
code: parserError.code,
message: `parse5 error code ${parserError.code}`,
}
formattedError.frame = generateCodeFrame(html, parserError.startOffset)
formattedError.loc = {
file: id,
line: parserError.startLine,
column: parserError.startCol,
}
frame: generateCodeFrame(html, parserError.startOffset),
loc: {
file: id,
line: parserError.startLine,
column: parserError.startCol,
},
} satisfies RollupError
return formattedError
}

Expand All @@ -266,15 +262,11 @@ function handleParseError(
// Allow self closing on non-void elements #10439
return
}
const parseError = {
loc: filePath,
frame: '',
...formatParseError(parserError, filePath, html),
}
const parseError = formatParseError(parserError, filePath, html)
throw new Error(
`Unable to parse HTML; ${parseError.message}\n at ${JSON.stringify(
parseError.loc,
)}\n${parseError.frame}`,
`Unable to parse HTML; ${parseError.message}\n` +
` at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` +
`${parseError.frame}`,
)
}

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ const devHtmlHook: IndexHtmlTransformHook = async (
)
}

await traverseHtml(html, htmlPath, (node) => {
await traverseHtml(html, filename, (node) => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This htmlPath argument is only passed to handleParseError, so it's safe to change.

export async function traverseHtml(
html: string,
filePath: string,
visitor: (node: DefaultTreeAdapterMap['node']) => void,
): Promise<void> {
// lazy load compiler
const { parse } = await import('parse5')
const ast = parse(html, {
sourceCodeLocationInfo: true,
onParseError: (e: ParserError) => {
handleParseError(e, html, filePath)
},
})
traverseNodes(ast, visitor)
}

if (!nodeIsElement(node)) {
return
}
Expand Down