优化js解析,更准确的把报错信息正确的输出

pull/5/head
yutent 2023-06-21 17:10:32 +08:00
parent f4a3ff6355
commit 1b3425196e
1 changed files with 18 additions and 12 deletions

View File

@ -111,7 +111,8 @@ export function parseJs(
code = '',
imports,
{ IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH, LEGACY_MODE } = {},
filename
filename,
linePatch = 0
) {
let fixedStyle = ''
let ASSETS_DIR = '/@/'
@ -125,16 +126,21 @@ export function parseJs(
code = Es.transformSync(code).code || ''
} catch (e) {
let err = e.errors.pop()
console.log('%s: %s', red('Uncaught SyntaxError'), err.text)
console.log(
' @ line %d: %s',
err.location.line,
cyan(err.location.lineText)
)
let lines = code.split('\n')
console.log('%s: %s', red('Uncaught SyntaxError'), red(err.text))
// 将上下文几行都打印出来
for (let i = err.location.line - 3; i <= err.location.line + 1; i++) {
console.log(
' @ line %d: %s',
i + linePatch,
err.location.line === i + 1 ? red(lines[i]) : lines[i]
)
}
console.log(
' @ %s:%d:%d',
blue(filename),
err.location.line,
err.location.line + linePatch - 1,
err.location.column
)
}
@ -283,6 +289,7 @@ export function compileVue(file, imports, options = {}) {
let js = code.match(JS_EXP)
let scss = [...code.matchAll(STYLE_EXP)]
let html = code.match(HTML_EXP) || ['', '']
let linePatch = code.slice(0, js.index).split('\n').length // js起始行数修正
let hash = md5(file)
let scopeId = 'data-' + hash
@ -317,9 +324,8 @@ export function compileVue(file, imports, options = {}) {
isCustomElement
}).code.replace('export function render', 'function render')
} catch (err) {
// console.log(err)
let tmp = html[1].split('\n')
let line = tmp[err.loc?.start.line - 1]
let lines = html[1].split('\n')
let line = lines[err.loc?.start.line - 1]
console.log('%s: %s', red('SyntaxError'), red(err.message))
console.log(
@ -360,7 +366,7 @@ function render(_ctx, _cache) {
CACHE[file] = { changed: false, js, html }
}
output += parseJs(js, imports, options, file).replace(
output += parseJs(js, imports, options, file, linePatch).replace(
'export default {',
`\n${
options.LEGACY_MODE ? '' : SHEETS_DEF