@@ -92,6 +92,12 @@ let typelessPackageJsonFilesWarnedAbout;
9292function getFileProtocolModuleFormat ( url , context = { __proto__ : null } , ignoreErrors ) {
9393 const { source } = context ;
9494 const ext = extname ( url ) ;
95+ const deduceFormat = ( fromSource , fromUrl ) => {
96+ const { existsSync, readFileSync } = require ( 'fs' ) ;
97+ const realSource = fromSource ?? existsSync ( fromUrl ) ? readFileSync ( fromUrl ) . toString ( ) : undefined ;
98+ return realSource ? // Do we have a source? check for module syntax
99+ ( containsModuleSyntax ( realSource , fileURLToPath ( fromUrl ) , fromUrl ) ? 'module' : 'commonjs' ) : 'commonjs' ;
100+ } ;
95101
96102 if ( ext === '.js' ) {
97103 const { type : packageType , pjsonPath } = getPackageScopeConfig ( url ) ;
@@ -113,9 +119,7 @@ function getFileProtocolModuleFormat(url, context = { __proto__: null }, ignoreE
113119 // `source` is undefined when this is called from `defaultResolve`;
114120 // but this gets called again from `defaultLoad`/`defaultLoadSync`.
115121 if ( getOptionValue ( '--experimental-detect-module' ) ) {
116- const format = source ?
117- ( containsModuleSyntax ( `${ source } ` , fileURLToPath ( url ) , url ) ? 'module' : 'commonjs' ) :
118- null ;
122+ const format = deduceFormat ( source , url ) ;
119123 if ( format === 'module' ) {
120124 // This module has a .js extension, a package.json with no `type` field, and ESM syntax.
121125 // Warn about the missing `type` field so that the user can avoid the performance penalty of detection.
@@ -155,12 +159,8 @@ function getFileProtocolModuleFormat(url, context = { __proto__: null }, ignoreE
155159 }
156160 default : { // The user did not pass `--experimental-default-type`.
157161 if ( getOptionValue ( '--experimental-detect-module' ) ) {
158- if ( ! source ) { return null ; }
159162 const format = getFormatOfExtensionlessFile ( url ) ;
160- if ( format === 'module' ) {
161- return containsModuleSyntax ( `${ source } ` , fileURLToPath ( url ) , url ) ? 'module' : 'commonjs' ;
162- }
163- return format ;
163+ return ( format === 'module' ) ? deduceFormat ( source , url ) : format ;
164164 }
165165 return 'commonjs' ;
166166 }
0 commit comments