@@ -10,13 +10,11 @@ const {
1010 ObjectKeys,
1111 PromisePrototypeCatch,
1212 PromiseReject,
13- RegExpPrototypeTest,
1413 SafeArrayIterator,
1514 SafeMap,
1615 SafeSet,
1716 StringPrototypeReplace,
1817 StringPrototypeSlice,
19- StringPrototypeSplit,
2018 StringPrototypeStartsWith,
2119 SyntaxErrorPrototype,
2220 globalThis : { WebAssembly } ,
@@ -31,8 +29,9 @@ function lazyTypes() {
3129const { readFileSync } = require ( 'fs' ) ;
3230const { extname, isAbsolute } = require ( 'path' ) ;
3331const {
32+ hasEsmSyntax,
33+ loadNativeModule,
3434 stripBOM,
35- loadNativeModule
3635} = require ( 'internal/modules/cjs/helpers' ) ;
3736const {
3837 Module : CJSModule ,
@@ -152,18 +151,14 @@ translators.set('module', async function moduleStrategy(url) {
152151 return module ;
153152} ) ;
154153
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' ) ) ) {
167162 // Emit the warning synchronously because we are in the middle of handling
168163 // a SyntaxError that will throw and likely terminate the process before an
169164 // asynchronous warning would be emitted.
@@ -200,7 +195,7 @@ translators.set('commonjs', async function commonjsStrategy(url, isMain) {
200195 try {
201196 exports = CJSModule . _load ( filename , undefined , isMain ) ;
202197 } catch ( err ) {
203- enrichCJSError ( err ) ;
198+ enrichCJSError ( err , undefined , filename ) ;
204199 throw err ;
205200 }
206201 }
0 commit comments