Skip to content

Commit

Permalink
fix: improve error message for HTML compilation error (fix #5769) (#5777
Browse files Browse the repository at this point in the history
)
  • Loading branch information
nurulhudaapon authored Dec 19, 2021
1 parent 7186857 commit 79d1397
Showing 1 changed file with 44 additions and 18 deletions.
62 changes: 44 additions & 18 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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'

Expand Down Expand Up @@ -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)
}
}

Expand All @@ -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}`
)
}

/**
Expand Down

0 comments on commit 79d1397

Please sign in to comment.