@@ -62,6 +62,7 @@ const {
6262 Boolean,
6363 Error,
6464 FunctionPrototypeBind,
65+ JSONStringify,
6566 MathMaxApply,
6667 NumberIsNaN,
6768 NumberParseFloat,
@@ -105,7 +106,9 @@ const {
105106const {
106107 isIdentifierStart,
107108 isIdentifierChar,
109+ parse : acornParse ,
108110} = require ( 'internal/deps/acorn/acorn/dist/acorn' ) ;
111+ const acornWalk = require ( 'internal/deps/acorn/acorn-walk/dist/walk' ) ;
109112const {
110113 decorateErrorStack,
111114 isError,
@@ -225,6 +228,28 @@ module.paths = CJSModule._nodeModulePaths(module.filename);
225228const writer = ( obj ) => inspect ( obj , writer . options ) ;
226229writer . options = { ...inspect . defaultOptions , showProxy : true } ;
227230
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+
228253function REPLServer ( prompt ,
229254 stream ,
230255 eval_ ,
@@ -690,7 +715,7 @@ function REPLServer(prompt,
690715 'module' ;
691716 if ( StringPrototypeIncludes ( e . message , importErrorStr ) ) {
692717 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 ) ) ;
694719 e . stack = SideEffectFreeRegExpPrototypeSymbolReplace (
695720 / S y n t a x E r r o r : .* \n / ,
696721 e . stack ,
0 commit comments