@@ -62,6 +62,7 @@ const {
62
62
Boolean,
63
63
Error,
64
64
FunctionPrototypeBind,
65
+ JSONStringify,
65
66
MathMaxApply,
66
67
NumberIsNaN,
67
68
NumberParseFloat,
@@ -105,7 +106,9 @@ const {
105
106
const {
106
107
isIdentifierStart,
107
108
isIdentifierChar,
109
+ parse : acornParse ,
108
110
} = require ( 'internal/deps/acorn/acorn/dist/acorn' ) ;
111
+ const acornWalk = require ( 'internal/deps/acorn/acorn-walk/dist/walk' ) ;
109
112
const {
110
113
decorateErrorStack,
111
114
isError,
@@ -225,6 +228,28 @@ module.paths = CJSModule._nodeModulePaths(module.filename);
225
228
const writer = ( obj ) => inspect ( obj , writer . options ) ;
226
229
writer . options = { ...inspect . defaultOptions , showProxy : true } ;
227
230
231
+ // Converts static import statement to dynamic import statement
232
+ const toDynamicImport = ( codeLine ) => {
233
+ let dynamicImportStatement = '' ;
234
+ const ast = acornParse ( codeLine , { __proto__ : null , sourceType : 'module' , ecmaVersion : 'latest' } ) ;
235
+ acornWalk . ancestor ( ast , {
236
+ ImportDeclaration ( node ) {
237
+ const awaitDynamicImport = `await import(${ JSONStringify ( node . source . value ) } );` ;
238
+ if ( node . specifiers . length === 0 ) {
239
+ dynamicImportStatement += awaitDynamicImport ;
240
+ } else if ( node . specifiers . length === 1 && node . specifiers [ 0 ] . type === 'ImportNamespaceSpecifier' ) {
241
+ dynamicImportStatement += `const ${ node . specifiers [ 0 ] . local . name } = ${ awaitDynamicImport } ` ;
242
+ } else {
243
+ const importNames = ArrayPrototypeJoin ( ArrayPrototypeMap ( node . specifiers , ( { local, imported } ) =>
244
+ ( local . name === imported ?. name ? local . name : `${ imported ?. name ?? 'default' } : ${ local . name } ` ) ,
245
+ ) , ', ' ) ;
246
+ dynamicImportStatement += `const { ${ importNames } } = ${ awaitDynamicImport } ` ;
247
+ }
248
+ } ,
249
+ } ) ;
250
+ return dynamicImportStatement ;
251
+ } ;
252
+
228
253
function REPLServer ( prompt ,
229
254
stream ,
230
255
eval_ ,
@@ -690,7 +715,7 @@ function REPLServer(prompt,
690
715
'module' ;
691
716
if ( StringPrototypeIncludes ( e . message , importErrorStr ) ) {
692
717
e . message = 'Cannot use import statement inside the Node.js ' +
693
- 'REPL, alternatively use dynamic import' ;
718
+ 'REPL, alternatively use dynamic import: ' + toDynamicImport ( self . lines . at ( - 1 ) ) ;
694
719
e . stack = SideEffectFreeRegExpPrototypeSymbolReplace (
695
720
/ S y n t a x E r r o r : .* \n / ,
696
721
e . stack ,
0 commit comments