@@ -10,13 +10,11 @@ const {
10
10
ObjectKeys,
11
11
PromisePrototypeCatch,
12
12
PromiseReject,
13
- RegExpPrototypeTest,
14
13
SafeArrayIterator,
15
14
SafeMap,
16
15
SafeSet,
17
16
StringPrototypeReplace,
18
17
StringPrototypeSlice,
19
- StringPrototypeSplit,
20
18
StringPrototypeStartsWith,
21
19
SyntaxErrorPrototype,
22
20
globalThis : { WebAssembly } ,
@@ -31,8 +29,9 @@ function lazyTypes() {
31
29
const { readFileSync } = require ( 'fs' ) ;
32
30
const { extname, isAbsolute } = require ( 'path' ) ;
33
31
const {
32
+ hasEsmSyntax,
33
+ loadNativeModule,
34
34
stripBOM,
35
- loadNativeModule
36
35
} = require ( 'internal/modules/cjs/helpers' ) ;
37
36
const {
38
37
Module : CJSModule ,
@@ -152,18 +151,14 @@ translators.set('module', async function moduleStrategy(url) {
152
151
return module ;
153
152
} ) ;
154
153
155
- function enrichCJSError ( err ) {
156
- if ( err == null || ObjectGetPrototypeOf ( err ) !== SyntaxErrorPrototype ) {
157
- return ;
158
- }
159
- const stack = StringPrototypeSplit ( err . stack , '\n' ) ;
160
- /*
161
- * The regular expression below targets the most common import statement
162
- * usage. However, some cases are not matching, cases like import statement
163
- * after a comment block and/or after a variable definition.
164
- */
165
- if ( StringPrototypeStartsWith ( err . message , 'Unexpected token \'export\'' ) ||
166
- RegExpPrototypeTest ( / ^ \s * i m p o r t (? = [ { ' " * ] ) \s * (? ! [ ( ] ) / , stack [ 1 ] ) ) {
154
+ /**
155
+ * @param {Error | any } err
156
+ * @param {string } [content] Content of the file, if known.
157
+ * @param {string } [filename] Useful only if `content` is unknown.
158
+ */
159
+ function enrichCJSError ( err , content , filename ) {
160
+ if ( err != null && ObjectGetPrototypeOf ( err ) === SyntaxErrorPrototype &&
161
+ hasEsmSyntax ( content || readFileSync ( filename , 'utf-8' ) ) ) {
167
162
// Emit the warning synchronously because we are in the middle of handling
168
163
// a SyntaxError that will throw and likely terminate the process before an
169
164
// asynchronous warning would be emitted.
@@ -200,7 +195,7 @@ translators.set('commonjs', async function commonjsStrategy(url, isMain) {
200
195
try {
201
196
exports = CJSModule . _load ( filename , undefined , isMain ) ;
202
197
} catch ( err ) {
203
- enrichCJSError ( err ) ;
198
+ enrichCJSError ( err , undefined , filename ) ;
204
199
throw err ;
205
200
}
206
201
}
0 commit comments