guybedford / es-module-lexer

Low-overhead lexer dedicated to ES module parsing for fast analysis
MIT License
930 stars 48 forks source link

Add line and column attributes to Parse Error #59

Closed remorses closed 3 years ago

remorses commented 3 years ago

Having those values makes it easier to identify the made the lexer fail, using code like

function tryParseImports(source, filename = '') {
    try {
        const [imports] = parse(source)
        return imports
    } catch (e) {
        const line = e.lineNumber
        throw new Error(
            `cannot parse ES imports in '${filename}', code is:\n${source
                .split('\n')
                .slice(abs(line - 1), line + 1)
                .join('  \n')}\n`,
        )
    }
}
remorses commented 3 years ago

Ok, i found you can do this

function tryParseImports(source, filename = '') {
    try {
        const [imports] = parse(source)
        return imports
    } catch (e) {
        const line = source.slice(0, e.idx).split('\n').length
        throw new Error(
            `cannot parse ES imports in '${filename}', code is:\n${source
                .split('\n')
                .slice(abs(line - 1), line + 1)
                .join('  \n')}\n`,
        )
    }
}
guybedford commented 3 years ago

If you don't add the try catch, you can just do parse(source, filename) and it will give you an error stack too.