@@ -816,20 +816,32 @@ Module.prototype.load = function(filename) {
816816 const url = `${ pathToFileURL ( filename ) } ` ;
817817 const module = ESMLoader . moduleMap . get ( url ) ;
818818 // Create module entry at load time to snapshot exports correctly
819- const exports = this . exports ;
820- // Called from cjs translator
821- if ( module !== undefined && module . module !== undefined ) {
822- if ( module . module . getStatus ( ) >= kInstantiated )
823- module . module . setExport ( 'default' , exports ) ;
824- } else { // preemptively cache
825- ESMLoader . moduleMap . set (
826- url ,
827- new ModuleJob ( ESMLoader , url , ( ) =>
828- new ModuleWrap ( function ( ) {
829- this . setExport ( 'default' , exports ) ;
830- } , [ 'default' ] , url )
831- )
832- ) ;
819+ const ext = path . extname ( filename ) ;
820+ // Only inject modules that are valid in the ES module system
821+ let injectIntoESM = ext === '.js' || ext === '.cjs' || ext === '.json' ||
822+ ext === '.node' ;
823+ if ( ext === '.js' ) {
824+ const pkg = readPackageScope ( filename ) ;
825+ // Do not inject CJS modules that break module type correctness
826+ if ( pkg && pkg . type === 'module' )
827+ injectIntoESM = false ;
828+ }
829+ if ( injectIntoESM ) {
830+ const exports = this . exports ;
831+ // Called from cjs translator
832+ if ( module !== undefined && module . module !== undefined ) {
833+ if ( module . module . getStatus ( ) >= kInstantiated )
834+ module . module . setExport ( 'default' , exports ) ;
835+ } else { // preemptively cache
836+ ESMLoader . moduleMap . set (
837+ url ,
838+ new ModuleJob ( ESMLoader , url , ( ) =>
839+ new ModuleWrap ( function ( ) {
840+ this . setExport ( 'default' , exports ) ;
841+ } , [ 'default' ] , url )
842+ )
843+ ) ;
844+ }
833845 }
834846 }
835847} ;
@@ -963,12 +975,6 @@ Module.prototype._compile = function(content, filename) {
963975
964976// Native extension for .js
965977Module . _extensions [ '.js' ] = function ( module , filename ) {
966- if ( experimentalModules && filename . endsWith ( '.js' ) ) {
967- const pkg = readPackageScope ( filename ) ;
968- if ( pkg && pkg . type === 'module' ) {
969- throw new ERR_REQUIRE_ESM ( filename ) ;
970- }
971- }
972978 const content = fs . readFileSync ( filename , 'utf8' ) ;
973979 module . _compile ( content , filename ) ;
974980} ;
0 commit comments