4343'use strict' ;
4444
4545const {
46+ ArrayPrototypeAt,
4647 ArrayPrototypeFilter,
4748 ArrayPrototypeFindIndex,
4849 ArrayPrototypeForEach,
@@ -62,6 +63,7 @@ const {
6263 Boolean,
6364 Error,
6465 FunctionPrototypeBind,
66+ JSONStringify,
6567 MathMaxApply,
6668 NumberIsNaN,
6769 NumberParseFloat,
@@ -104,7 +106,9 @@ const {
104106const {
105107 isIdentifierStart,
106108 isIdentifierChar,
109+ parse : acornParse ,
107110} = require ( 'internal/deps/acorn/acorn/dist/acorn' ) ;
111+ const acornWalk = require ( 'internal/deps/acorn/acorn-walk/dist/walk' ) ;
108112const {
109113 decorateErrorStack,
110114 isError,
@@ -223,6 +227,28 @@ module.paths = CJSModule._nodeModulePaths(module.filename);
223227const writer = ( obj ) => inspect ( obj , writer . options ) ;
224228writer . options = { ...inspect . defaultOptions , showProxy : true } ;
225229
230+ // Converts static import statement to dynamic import statement
231+ const toDynamicImport = ( codeLine ) => {
232+ let dynamicImportStatement = '' ;
233+ const ast = acornParse ( codeLine , { __proto__ : null , sourceType : 'module' , ecmaVersion : 'latest' } ) ;
234+ acornWalk . ancestor ( ast , {
235+ ImportDeclaration ( node ) {
236+ const awaitDynamicImport = `await import(${ JSONStringify ( node . source . value ) } );` ;
237+ if ( node . specifiers . length === 0 ) {
238+ dynamicImportStatement += awaitDynamicImport ;
239+ } else if ( node . specifiers . length === 1 && node . specifiers [ 0 ] . type === 'ImportNamespaceSpecifier' ) {
240+ dynamicImportStatement += `const ${ node . specifiers [ 0 ] . local . name } = ${ awaitDynamicImport } ` ;
241+ } else {
242+ const importNames = ArrayPrototypeJoin ( ArrayPrototypeMap ( node . specifiers , ( { local, imported } ) =>
243+ ( local . name === imported ?. name ? local . name : `${ imported ?. name ?? 'default' } : ${ local . name } ` ) ,
244+ ) , ', ' ) ;
245+ dynamicImportStatement += `const { ${ importNames } } = ${ awaitDynamicImport } ` ;
246+ }
247+ } ,
248+ } ) ;
249+ return dynamicImportStatement ;
250+ } ;
251+
226252function REPLServer ( prompt ,
227253 stream ,
228254 eval_ ,
@@ -684,7 +710,7 @@ function REPLServer(prompt,
684710 'module' ;
685711 if ( StringPrototypeIncludes ( e . message , importErrorStr ) ) {
686712 e . message = 'Cannot use import statement inside the Node.js ' +
687- 'REPL, alternatively use dynamic import' ;
713+ 'REPL, alternatively use dynamic import: ' + toDynamicImport ( ArrayPrototypeAt ( self . lines , - 1 ) ) ;
688714 e . stack = SideEffectFreeRegExpPrototypeSymbolReplace (
689715 / S y n t a x E r r o r : .* \n / ,
690716 e . stack ,
0 commit comments