Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

esm: make dynamic import work in the REPL #29437

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion lib/repl.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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);
});