Skip to content

Commit

Permalink
esm: make dynamic import work in the REPL
Browse files Browse the repository at this point in the history
PR-URL: #29437
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: David Carlier <devnexen@gmail.com>
  • Loading branch information
bfarias-godaddy committed Sep 6, 2019
1 parent 63b056d commit cdebd32
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/repl.js
Expand Up @@ -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;
Expand Down Expand Up @@ -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) &&
Expand All @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions 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);
});

0 comments on commit cdebd32

Please sign in to comment.