Skip to content

Commit

Permalink
fix: improve error message for HTML compilation error (fix #5769)
Browse files Browse the repository at this point in the history
  • Loading branch information
nurulhudaapon committed Nov 20, 2021
1 parent 5588eb9 commit 2543e16
Showing 1 changed file with 39 additions and 18 deletions.
57 changes: 39 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 { Plugin } from '../plugin'
import { ViteDevServer } from '../server'
import { OutputAsset, OutputBundle, OutputChunk } from 'rollup'
import { OutputAsset, OutputBundle, OutputChunk, RollupError } from 'rollup'
import {
cleanUrl,
generateCodeFrame,
Expand All @@ -25,7 +25,8 @@ import {
AttributeNode,
NodeTransform,
NodeTypes,
ElementNode
ElementNode,
CompilerError
} from '@vue/compiler-dom'

const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/
Expand Down Expand Up @@ -114,14 +115,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 +142,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 2543e16

Please sign in to comment.