diff --git a/lib/repl.js b/lib/repl.js index 2f82c2ca49fc71..404527d85e147f 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -279,6 +279,12 @@ function REPLServer(prompt, } function defaultEval(code, context, file, cb) { + const { getOptionValue } = require('internal/options'); + const experimentalModules = getOptionValue('--experimental-modules'); + const asyncESM = experimentalModules ? + require('internal/process/esm_loader') : + null; + let result, script, wrappedErr; let err = null; let wrappedCmd = false; @@ -312,6 +318,12 @@ function REPLServer(prompt, if (code === '\n') return cb(null); + let pwd; + try { + const { pathToFileURL } = require('url'); + pwd = pathToFileURL(process.cwd()).href; + } catch { + } while (true) { try { if (!/^\s*$/.test(code) && @@ -322,7 +334,12 @@ function REPLServer(prompt, } script = vm.createScript(code, { filename: file, - displayErrors: true + displayErrors: true, + importModuleDynamically: experimentalModules ? + async (specifier) => { + return (await asyncESM.loaderPromise).import(specifier, pwd); + } : + undefined }); } catch (e) { debug('parse error %j', code, e); diff --git a/test/es-module/test-esm-repl.js b/test/es-module/test-esm-repl.js new file mode 100644 index 00000000000000..daef48d8e1f58b --- /dev/null +++ b/test/es-module/test-esm-repl.js @@ -0,0 +1,19 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { spawn } = require('child_process'); + +const child = spawn(process.execPath, [ + '--experimental-modules', + '--interactive' +]); +child.stdin.end(` +import('fs').then( + ns => ns.default === require('fs') ? 0 : 1, + _ => 2 +).then(process.exit) +`); + +child.on('exit', (code) => { + assert.strictEqual(code, 0); +});