diff --git a/lib/esm-utils.js b/lib/esm-utils.js index 604f883d9a..eebeb9322b 100644 --- a/lib/esm-utils.js +++ b/lib/esm-utils.js @@ -3,7 +3,29 @@ const url = require('url'); const formattedImport = async file => { if (path.isAbsolute(file)) { - return import(url.pathToFileURL(file)); + try { + return await import(url.pathToFileURL(file)); + } catch (err) { + // This is a hack created because ESM in Node.js (at least in Node v15.5.1) does not emit + // the location of the syntax error in the error thrown. + // This is problematic because the user can't see what file has the problem, + // so we add the file location to the error. + // This `if` should be removed once Node.js fixes the problem. + if ( + err instanceof SyntaxError && + err.message && + err.stack && + !err.stack.includes(file) + ) { + const newErrorWithFilename = new SyntaxError(err.message); + newErrorWithFilename.stack = err.stack.replace( + /^SyntaxError/, + `SyntaxError[ @${file} ]` + ); + throw newErrorWithFilename; + } + throw err; + } } return import(file); };