From cdebd3246102be2a79546806161d121e5d3e3294 Mon Sep 17 00:00:00 2001 From: Bradley Farias Date: Wed, 4 Sep 2019 11:19:14 -0500 Subject: [PATCH] esm: make dynamic import work in the REPL PR-URL: https://github.com/nodejs/node/pull/29437 Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: Gus Caplan Reviewed-By: David Carlier --- lib/repl.js | 19 ++++++++++++++++++- test/es-module/test-esm-repl.js | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 test/es-module/test-esm-repl.js diff --git a/lib/repl.js b/lib/repl.js index d1b9a91df648dc..4dabe2110dbf7c 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); +});