1
1
'use strict' ;
2
2
const {
3
- RegExpPrototypeExec,
4
3
ObjectAssign,
5
4
ObjectCreate,
6
5
ObjectPrototypeHasOwnProperty,
7
6
PromisePrototypeThen,
8
7
PromiseResolve,
8
+ RegExpPrototypeExec,
9
+ StringPrototypeSlice,
9
10
} = primordials ;
10
- const { extname } = require ( 'path' ) ;
11
+ const { basename , extname, relative } = require ( 'path' ) ;
11
12
const { getOptionValue } = require ( 'internal/options' ) ;
12
13
const { fetchModule } = require ( 'internal/modules/esm/fetch_module' ) ;
13
14
const {
@@ -20,7 +21,7 @@ const experimentalNetworkImports =
20
21
getOptionValue ( '--experimental-network-imports' ) ;
21
22
const experimentalSpecifierResolution =
22
23
getOptionValue ( '--experimental-specifier-resolution' ) ;
23
- const { getPackageType } = require ( 'internal/modules/esm/resolve' ) ;
24
+ const { getPackageType, getPackageScopeConfig } = require ( 'internal/modules/esm/resolve' ) ;
24
25
const { URL , fileURLToPath } = require ( 'internal/url' ) ;
25
26
const { ERR_UNKNOWN_FILE_EXTENSION } = require ( 'internal/errors' ) . codes ;
26
27
@@ -48,7 +49,8 @@ function getDataProtocolModuleFormat(parsed) {
48
49
* @returns {string }
49
50
*/
50
51
function getFileProtocolModuleFormat ( url , context , ignoreErrors ) {
51
- const ext = extname ( url . pathname ) ;
52
+ const filepath = fileURLToPath ( url ) ;
53
+ const ext = extname ( filepath ) ;
52
54
if ( ext === '.js' ) {
53
55
return getPackageType ( url ) === 'module' ? 'module' : 'commonjs' ;
54
56
}
@@ -59,7 +61,19 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) {
59
61
if ( experimentalSpecifierResolution !== 'node' ) {
60
62
// Explicit undefined return indicates load hook should rerun format check
61
63
if ( ignoreErrors ) return undefined ;
62
- throw new ERR_UNKNOWN_FILE_EXTENSION ( ext , fileURLToPath ( url ) ) ;
64
+ let suggestion = '' ;
65
+ if ( getPackageType ( url ) === 'module' && ext === '' ) {
66
+ const config = getPackageScopeConfig ( url ) ;
67
+ const fileBasename = basename ( filepath ) ;
68
+ const relativePath = StringPrototypeSlice ( relative ( config . pjsonPath , filepath ) , 1 ) ;
69
+ suggestion = 'Loading extensionless files is not supported inside of ' +
70
+ '"type":"module" package.json contexts. The package.json file ' +
71
+ `${ config . pjsonPath } caused this "type":"module" context. Try ` +
72
+ `changing ${ filepath } to have a file extension. Note the "bin" ` +
73
+ 'field of package.json can point to a file with an extension, for example ' +
74
+ `{"type":"module","bin":{"${ fileBasename } ":"${ relativePath } .js"}}` ;
75
+ }
76
+ throw new ERR_UNKNOWN_FILE_EXTENSION ( ext , filepath , suggestion ) ;
63
77
}
64
78
65
79
return getLegacyExtensionFormat ( ext ) ?? null ;
0 commit comments