Skip to content

Commit

Permalink
fix: handle edge cases for toDynamicImport
Browse files Browse the repository at this point in the history
  • Loading branch information
hemanth committed May 31, 2023
1 parent 3bb9b4e commit 653dd2b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
16 changes: 9 additions & 7 deletions lib/repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ const {
ArrayPrototypeSome,
ArrayPrototypeSort,
ArrayPrototypeSplice,
ArrayPrototypeToString,
ArrayPrototypeUnshift,
Boolean,
Error,
Expand Down Expand Up @@ -233,25 +232,28 @@ writer.options = { ...inspect.defaultOptions, showProxy: true };
const toDynamicImport = (codeLine) => {
let dynamicImportStatement = '';
let moduleName = '';
const toCamelCase = (str) => str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
const ast = acornParse(codeLine, { sourceType: 'module', ecmaVersion: 'latest' });
const toCamelCase = (str) => str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
acornWalk.ancestor(ast, {
ImportDeclaration: (node) => {
ImportDeclaration(node) {
const importedModules = node.source.value;
const importedSpecifiers = node.specifiers.map((specifier) => specifier.local.name);
const importedSpecifiers = node.specifiers.map((specifier) => {
if (specifier.local.name === specifier?.imported?.name) {
return specifier.local.name;
}
return `${specifier?.imported?.name ? specifier.imported.name + ':' : ''}${specifier.local.name}`;
});
if (importedSpecifiers.length > 1) {
moduleName = `{${importedSpecifiers.join(',')}}`;
} else {
const formattedSpecifiers = importedSpecifiers.length ? ArrayPrototypeToString(importedSpecifiers) : '';
moduleName = toCamelCase(formattedSpecifiers || importedModules);
moduleName = toCamelCase(importedSpecifiers.length ? importedSpecifiers.toString() : importedModules);
}
dynamicImportStatement += `const ${moduleName} = await import('${importedModules}');`;
},
});
return dynamicImportStatement;
};


function REPLServer(prompt,
stream,
eval_,
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,17 @@ alternatively use dynamic import: const name = await import(\'module-name\');',
alternatively use dynamic import: const moduleName = await import(\'module-name\');',
]
},
{
send: 'import { export1 as localName1, export2 } from "bar";',
expect: [
kSource,
kArrow,
'',
'Uncaught:',
'SyntaxError: Cannot use import statement inside the Node.js REPL, \
alternatively use dynamic import: const {export1:localName1,export2} = await import("bar");',
]
},
];

(async function() {
Expand Down

0 comments on commit 653dd2b

Please sign in to comment.