@@ -352,16 +352,38 @@ class Runtime {
352
352
importModuleDynamically : (
353
353
specifier : string ,
354
354
referencingModule : VMModule ,
355
- ) =>
356
- this . loadEsmModule (
357
- this . _resolveModule ( referencingModule . identifier , specifier ) ,
358
- ) ,
355
+ ) => {
356
+ const resolved = this . _resolveModule (
357
+ referencingModule . identifier ,
358
+ specifier ,
359
+ ) ;
360
+ if (
361
+ this . _resolver . isCoreModule ( resolved ) ||
362
+ this . unstable_shouldLoadAsEsm ( resolved )
363
+ ) {
364
+ return this . loadEsmModule ( resolved ) ;
365
+ }
366
+
367
+ return this . loadCjsAsEsm (
368
+ referencingModule . identifier ,
369
+ resolved ,
370
+ context ,
371
+ ) ;
372
+ } ,
359
373
initializeImportMeta ( meta : ImportMeta ) {
360
374
meta . url = pathToFileURL ( modulePath ) . href ;
361
375
} ,
362
376
} ) ;
363
377
364
378
this . _esmoduleRegistry . set ( cacheKey , module ) ;
379
+
380
+ await module . link ( ( specifier : string , referencingModule : VMModule ) =>
381
+ this . loadEsmModule (
382
+ this . _resolveModule ( referencingModule . identifier , specifier ) ,
383
+ ) ,
384
+ ) ;
385
+
386
+ await module . evaluate ( ) ;
365
387
}
366
388
367
389
const module = this . _esmoduleRegistry . get ( cacheKey ) ;
@@ -382,13 +404,33 @@ class Runtime {
382
404
383
405
const modulePath = this . _resolveModule ( from , moduleName ) ;
384
406
385
- const module = await this . loadEsmModule ( modulePath ) ;
386
- await module . link ( ( specifier : string , referencingModule : VMModule ) =>
387
- this . loadEsmModule (
388
- this . _resolveModule ( referencingModule . identifier , specifier ) ,
389
- ) ,
407
+ return this . loadEsmModule ( modulePath ) ;
408
+ }
409
+
410
+ private async loadCjsAsEsm (
411
+ from : Config . Path ,
412
+ modulePath : Config . Path ,
413
+ context : VMContext ,
414
+ ) {
415
+ // CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503
416
+ const cjs = this . requireModuleOrMock ( from , modulePath ) ;
417
+
418
+ const module = new SyntheticModule (
419
+ [ 'default' ] ,
420
+ function ( ) {
421
+ // @ts -ignore: TS doesn't know what `this` is
422
+ this . setExport ( 'default' , cjs ) ;
423
+ } ,
424
+ { context, identifier : modulePath } ,
390
425
) ;
426
+
427
+ await module . link ( ( ) => {
428
+ throw new Error ( 'This should never happen' ) ;
429
+ } ) ;
430
+
391
431
await module . evaluate ( ) ;
432
+
433
+ return module ;
392
434
}
393
435
394
436
requireModule < T = unknown > (
0 commit comments