From fa51418516e740d7aad839f448f51fde6f5edd43 Mon Sep 17 00:00:00 2001 From: Outsider Date: Thu, 21 Jan 2021 03:44:32 +0900 Subject: [PATCH] show where syntax error from with ESM Signed-off-by: Outsider --- lib/esm-utils.js | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/lib/esm-utils.js b/lib/esm-utils.js index 604f883d9a..8a054e014a 100644 --- a/lib/esm-utils.js +++ b/lib/esm-utils.js @@ -2,10 +2,40 @@ const path = require('path'); const url = require('url'); const formattedImport = async file => { - if (path.isAbsolute(file)) { - return import(url.pathToFileURL(file)); + try { + if (path.isAbsolute(file)) { + return await import(url.pathToFileURL(file)); + } + return import(file); + } catch (err) { + if (err.name === 'SyntaxError') { + // This is a hack to print where syntax error is from. + // In dynamic import, it doesn't contain filename linenumber in errer.stack + // See https://github.com/nodejs/modules/issues/471 + // FIXME: remove this hack after nodejs suppurt + return await new Promise((resolve, reject) => { + const {spawn} = require('child_process'); + + const proc = spawn(process.execPath, [ + '--unhandled-rejections=throw', + '-e', + `import('${file}')` + ]); + + let errMsg = ''; + + proc.stderr.on('data', data => { + errMsg += data; + }); + + proc.on('exit', () => { + const err = new Error(errMsg); + err.stack = errMsg; + reject(err); + }); + }); + } } - return import(file); }; exports.requireOrImport = async file => {