@@ -4,17 +4,20 @@ const {
4
4
ArrayPrototypeJoin,
5
5
ArrayPrototypeMap,
6
6
ArrayPrototypePush,
7
+ ArrayPrototypeSome,
7
8
FunctionPrototype,
8
9
ObjectSetPrototypeOf,
9
10
PromiseAll,
10
11
PromiseResolve,
11
12
PromisePrototypeCatch,
12
13
ReflectApply,
14
+ RegExpPrototypeTest,
13
15
SafeSet,
14
16
StringPrototypeIncludes,
15
17
StringPrototypeMatch,
16
18
StringPrototypeReplace,
17
19
StringPrototypeSplit,
20
+ StringPrototypeStartsWith,
18
21
} = primordials ;
19
22
20
23
const { ModuleWrap } = internalBinding ( 'module_wrap' ) ;
@@ -27,6 +30,19 @@ const noop = FunctionPrototype;
27
30
28
31
let hasPausedEntry = false ;
29
32
33
+ const CJSGlobalLike = [
34
+ 'require' ,
35
+ 'module' ,
36
+ 'exports' ,
37
+ '__filename' ,
38
+ '__dirname' ,
39
+ ] ;
40
+ const isCommonJSGlobalLikeNotDefinedError = ( errorMessage ) =>
41
+ ArrayPrototypeSome (
42
+ CJSGlobalLike ,
43
+ ( globalLike ) => errorMessage === `${ globalLike } is not defined`
44
+ ) ;
45
+
30
46
/* A ModuleJob tracks the loading of a single Module, and the ModuleJobs of
31
47
* its dependencies, over time. */
32
48
class ModuleJob {
@@ -149,7 +165,32 @@ class ModuleJob {
149
165
await this . instantiate ( ) ;
150
166
const timeout = - 1 ;
151
167
const breakOnSigint = false ;
152
- await this . module . evaluate ( timeout , breakOnSigint ) ;
168
+ try {
169
+ await this . module . evaluate ( timeout , breakOnSigint ) ;
170
+ } catch ( e ) {
171
+ if ( e ?. name === 'ReferenceError' &&
172
+ isCommonJSGlobalLikeNotDefinedError ( e . message ) ) {
173
+ e . message += ' in ES module scope' ;
174
+
175
+ if ( StringPrototypeStartsWith ( e . message , 'require ' ) ) {
176
+ e . message += ', you can use import instead' ;
177
+ }
178
+
179
+ const packageConfig =
180
+ StringPrototypeStartsWith ( this . module . url , 'file://' ) &&
181
+ RegExpPrototypeTest ( / \. j s ( \? [ ^ # ] * ) ? ( # .* ) ? $ / , this . module . url ) &&
182
+ require ( 'internal/modules/esm/resolve' )
183
+ . getPackageScopeConfig ( this . module . url ) ;
184
+ if ( packageConfig . type === 'module' ) {
185
+ e . message +=
186
+ '\nThis file is being treated as an ES module because it has a ' +
187
+ `'.js' file extension and '${ packageConfig . pjsonPath } ' contains ` +
188
+ '"type": "module". To treat it as a CommonJS script, rename it ' +
189
+ 'to use the \'.cjs\' file extension.' ;
190
+ }
191
+ }
192
+ throw e ;
193
+ }
153
194
return { module : this . module } ;
154
195
}
155
196
}
0 commit comments