@@ -260,7 +260,10 @@ function readPackageScope(checkPath) {
260260 if ( checkPath . endsWith ( path . sep + 'node_modules' ) )
261261 return false ;
262262 const pjson = readPackage ( checkPath ) ;
263- if ( pjson ) return pjson ;
263+ if ( pjson ) return {
264+ path : checkPath ,
265+ data : pjson
266+ } ;
264267 }
265268 return false ;
266269}
@@ -959,13 +962,32 @@ Module.prototype._compile = function(content, filename) {
959962 return result ;
960963} ;
961964
962-
963965// Native extension for .js
966+ let warnRequireESM = true ;
964967Module . _extensions [ '.js' ] = function ( module , filename ) {
965- if ( experimentalModules && filename . endsWith ( '.js' ) ) {
968+ if ( filename . endsWith ( '.js' ) ) {
966969 const pkg = readPackageScope ( filename ) ;
967- if ( pkg && pkg . type === 'module' ) {
968- throw new ERR_REQUIRE_ESM ( filename ) ;
970+ if ( pkg && pkg . data && pkg . data . type === 'module' ) {
971+ if ( warnRequireESM ) {
972+ const parentPath = module . parent && module . parent . filename ;
973+ const basename = parentPath &&
974+ path . basename ( filename ) === path . basename ( parentPath ) ?
975+ filename : path . basename ( filename ) ;
976+ process . emitWarning (
977+ 'require() of ES modules is not supported.\nrequire() of ' +
978+ `${ filename } ${ parentPath ? `from ${ module . parent . filename } ` : '' } ` +
979+ 'is an ES module file as it is a .js file whose nearest parent ' +
980+ 'package.json contains "type": "module" which defines all .js ' +
981+ 'files in that package scope as ES modules.\nInstead rename ' +
982+ `${ basename } to end in .cjs, change the requiring code to use ` +
983+ 'import(), or remove "type": "module" from ' +
984+ `${ path . resolve ( pkg . path , 'package.json' ) } .`
985+ ) ;
986+ warnRequireESM = false ;
987+ }
988+ if ( experimentalModules ) {
989+ throw new ERR_REQUIRE_ESM ( filename ) ;
990+ }
969991 }
970992 }
971993 const content = fs . readFileSync ( filename , 'utf8' ) ;
0 commit comments