Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve error message for HTML compilation error (fix #5769) #5777

Merged
merged 4 commits into from
Dec 19, 2021
Merged
Changes from 2 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
58 changes: 40 additions & 18 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
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,
Expand All @@ -24,7 +24,9 @@ import { modulePreloadPolyfillId } from './modulePreloadPolyfill'
import type {
AttributeNode,
NodeTransform,
ElementNode
NodeTypes,
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
ElementNode,
CompilerError
} from '@vue/compiler-dom'
import { NodeTypes } from '@vue/compiler-dom'

Expand Down Expand Up @@ -114,14 +116,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)
}
}

Expand All @@ -148,17 +143,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}`
)
}

/**
Expand Down