@@ -259,7 +259,10 @@ function readPackageScope(checkPath) {
259
259
if ( checkPath . endsWith ( path . sep + 'node_modules' ) )
260
260
return false ;
261
261
const pjson = readPackage ( checkPath ) ;
262
- if ( pjson ) return pjson ;
262
+ if ( pjson ) return {
263
+ path : checkPath ,
264
+ data : pjson
265
+ } ;
263
266
}
264
267
return false ;
265
268
}
@@ -959,13 +962,32 @@ Module.prototype._compile = function(content, filename) {
959
962
return result ;
960
963
} ;
961
964
962
-
963
965
// Native extension for .js
966
+ let warnRequireESM = true ;
964
967
Module . _extensions [ '.js' ] = function ( module , filename ) {
965
- if ( experimentalModules && filename . endsWith ( '.js' ) ) {
968
+ if ( filename . endsWith ( '.js' ) ) {
966
969
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
+ }
969
991
}
970
992
}
971
993
const content = fs . readFileSync ( filename , 'utf8' ) ;
0 commit comments