Skip to content

Commit 653dd2b

Browse files
committed
fix: handle edge cases for toDynamicImport
1 parent 3bb9b4e commit 653dd2b

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

lib/repl.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ const {
5858
ArrayPrototypeSome,
5959
ArrayPrototypeSort,
6060
ArrayPrototypeSplice,
61-
ArrayPrototypeToString,
6261
ArrayPrototypeUnshift,
6362
Boolean,
6463
Error,
@@ -233,25 +232,28 @@ writer.options = { ...inspect.defaultOptions, showProxy: true };
233232
const toDynamicImport = (codeLine) => {
234233
let dynamicImportStatement = '';
235234
let moduleName = '';
236-
const toCamelCase = (str) => str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
237235
const ast = acornParse(codeLine, { sourceType: 'module', ecmaVersion: 'latest' });
236+
const toCamelCase = (str) => str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
238237
acornWalk.ancestor(ast, {
239-
ImportDeclaration: (node) => {
238+
ImportDeclaration(node) {
240239
const importedModules = node.source.value;
241-
const importedSpecifiers = node.specifiers.map((specifier) => specifier.local.name);
240+
const importedSpecifiers = node.specifiers.map((specifier) => {
241+
if (specifier.local.name === specifier?.imported?.name) {
242+
return specifier.local.name;
243+
}
244+
return `${specifier?.imported?.name ? specifier.imported.name + ':' : ''}${specifier.local.name}`;
245+
});
242246
if (importedSpecifiers.length > 1) {
243247
moduleName = `{${importedSpecifiers.join(',')}}`;
244248
} else {
245-
const formattedSpecifiers = importedSpecifiers.length ? ArrayPrototypeToString(importedSpecifiers) : '';
246-
moduleName = toCamelCase(formattedSpecifiers || importedModules);
249+
moduleName = toCamelCase(importedSpecifiers.length ? importedSpecifiers.toString() : importedModules);
247250
}
248251
dynamicImportStatement += `const ${moduleName} = await import('${importedModules}');`;
249252
},
250253
});
251254
return dynamicImportStatement;
252255
};
253256

254-
255257
function REPLServer(prompt,
256258
stream,
257259
eval_,

test/parallel/test-repl.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -855,6 +855,17 @@ alternatively use dynamic import: const name = await import(\'module-name\');',
855855
alternatively use dynamic import: const moduleName = await import(\'module-name\');',
856856
]
857857
},
858+
{
859+
send: 'import { export1 as localName1, export2 } from "bar";',
860+
expect: [
861+
kSource,
862+
kArrow,
863+
'',
864+
'Uncaught:',
865+
'SyntaxError: Cannot use import statement inside the Node.js REPL, \
866+
alternatively use dynamic import: const {export1:localName1,export2} = await import("bar");',
867+
]
868+
},
858869
];
859870

860871
(async function() {

0 commit comments

Comments
 (0)