66 ObjectPrototypeHasOwnProperty,
77 PromisePrototypeThen,
88 PromiseResolve,
9+ StringPrototypeSlice,
910} = primordials ;
10- const { extname } = require ( 'path' ) ;
11+ const { basename , extname, relative } = require ( 'path' ) ;
1112const { getOptionValue } = require ( 'internal/options' ) ;
1213const { fetchModule } = require ( 'internal/modules/esm/fetch_module' ) ;
1314const {
@@ -20,7 +21,7 @@ const experimentalNetworkImports =
2021 getOptionValue ( '--experimental-network-imports' ) ;
2122const experimentalSpecifierResolution =
2223 getOptionValue ( '--experimental-specifier-resolution' ) ;
23- const { getPackageType } = require ( 'internal/modules/esm/resolve' ) ;
24+ const { getPackageType, getPackageScopeConfig } = require ( 'internal/modules/esm/resolve' ) ;
2425const { URL , fileURLToPath } = require ( 'internal/url' ) ;
2526const { ERR_UNKNOWN_FILE_EXTENSION } = require ( 'internal/errors' ) . codes ;
2627
@@ -52,7 +53,8 @@ function getDataProtocolModuleFormat(parsed) {
5253 * @returns {string }
5354 */
5455function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
55- const ext = extname ( url . pathname ) ;
56+ const filepath = fileURLToPath ( url ) ;
57+ const ext = extname ( filepath ) ;
5658 if ( ext === '.js' ) {
5759 return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
5860 }
@@ -63,7 +65,19 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
6365 if ( experimentalSpecifierResolution !== 'node' ) {
6466 // Explicit undefined return indicates load hook should rerun format check
6567 if ( ignoreErrors ) return undefined ;
66- throw new ERR_UNKNOWN_FILE_EXTENSION ( ext , fileURLToPath ( url ) ) ;
68+ let suggestion = '' ;
69+ if ( getPackageType ( url ) === 'module' && ext === '' ) {
70+ const config = getPackageScopeConfig ( url ) ;
71+ const fileBasename = basename ( filepath ) ;
72+ const relativePath = StringPrototypeSlice ( relative ( config . pjsonPath , filepath ) , 1 ) ;
73+ suggestion = 'Loading extensionless files is not supported inside of ' +
74+ '"type":"module" package.json contexts. The package.json file ' +
75+ `${ config . pjsonPath } caused this "type":"module" context. Try ` +
76+ `changing ${ filepath } to have a file extension. Note the "bin" ` +
77+ 'field of package.json can point to a file with an extension, for example ' +
78+ `{"type":"module","bin":{"${ fileBasename } ":"${ relativePath } .js"}}` ;
79+ }
80+ throw new ERR_UNKNOWN_FILE_EXTENSION ( ext , filepath , suggestion ) ;
6781 }
6882
6983 return getLegacyExtensionFormat ( ext ) ?? null ;
0 commit comments