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