From 18f01ddcb5c3621a01d97a4dc5e3ac74fbacdc78 Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Wed, 27 May 2020 12:05:55 -0400 Subject: [PATCH] repl: improve static import error message in repl Currently the error is rather ambiguous and does not inform folks that static import is not supported in the repl. This overrides the default error message with one that is more informative. Closes: https://github.com/nodejs/node/issues/33576 PR-URL: https://github.com/nodejs/node/pull/33588 Fixes: https://github.com/nodejs/node/issues/33576 Reviewed-By: James M Snell Reviewed-By: Guy Bedford Reviewed-By: Ruben Bridgewater --- lib/repl.js | 9 +++++++++ test/parallel/test-repl.js | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/repl.js b/lib/repl.js index a37e8e0be7bab2..10ca72f0e79d26 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -58,6 +58,7 @@ const { PromiseRace, RegExp, Set, + StringPrototypeIncludes, Symbol, WeakSet, } = primordials; @@ -549,6 +550,14 @@ function REPLServer(prompt, e.stack = e.stack .replace(/^REPL\d+:\d+\r?\n/, '') .replace(/^\s+at\s.*\n?/gm, ''); + const importErrorStr = 'Cannot use import statement outside a ' + + 'module'; + if (StringPrototypeIncludes(e.message, importErrorStr)) { + e.message = 'Cannot use import statement inside the Node.js ' + + 'repl, alternatively use dynamic import'; + e.stack = e.stack.replace(/SyntaxError:.*\n/, + `SyntaxError: ${e.message}\n`); + } } else if (self.replMode === exports.REPL_MODE_STRICT) { e.stack = e.stack.replace(/(\s+at\s+REPL\d+:)(\d+)/, (_, pre, line) => pre + (line - 1)); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index 76dec355381299..ee1650be1c9140 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -805,6 +805,16 @@ const tcpTests = [ { send: `require(${JSON.stringify(moduleFilename)}).number`, expect: '42' + }, + { + send: 'import comeOn from \'fhqwhgads\'', + expect: [ + kSource, + kArrow, + '', + 'Uncaught:', + /^SyntaxError: .* dynamic import/ + ] } ];