99 ObjectKeys,
1010 PromisePrototypeCatch,
1111 PromiseReject,
12+ RegExpPrototypeTest,
1213 SafeMap,
1314 SafeSet,
1415 StringPrototypeReplace,
16+ StringPrototypeSplit,
17+ StringPrototypeStartsWith,
1518} = primordials ;
1619
1720let _TYPES = null ;
@@ -57,6 +60,7 @@ const cjsParse = require('internal/deps/cjs-module-lexer/lexer');
5760
5861const translators = new SafeMap ( ) ;
5962exports . translators = translators ;
63+ exports . enrichCJSError = enrichCJSError ;
6064
6165let DECODER = null ;
6266function assertBufferSource ( body , allowString , hookName ) {
@@ -130,6 +134,29 @@ translators.set('module', async function moduleStrategy(url) {
130134 return module ;
131135} ) ;
132136
137+
138+ function enrichCJSError ( err ) {
139+ const stack = StringPrototypeSplit ( err . stack , '\n' ) ;
140+ /*
141+ The regular expression below targets the most common import statement
142+ usage. However, some cases are not matching, cases like import statement
143+ after a comment block and/or after a variable definition.
144+ */
145+ if ( StringPrototypeStartsWith ( err . message , 'Unexpected token \'export\'' ) ||
146+ ( RegExpPrototypeTest ( / ^ \s * i m p o r t (? = [ { ' " * ] ) \s * (? ! [ ( ] ) / , stack [ 1 ] ) ) ) {
147+ // Emit the warning synchronously because we are in the middle of handling
148+ // a SyntaxError that will throw and likely terminate the process before an
149+ // asynchronous warning would be emitted.
150+ process . emitWarning (
151+ 'To load an ES module, set "type": "module" in the package.json or use ' +
152+ 'the .mjs extension.' ,
153+ undefined ,
154+ undefined ,
155+ undefined ,
156+ true ) ;
157+ }
158+ }
159+
133160// Strategy for loading a node-style CommonJS module
134161const isWindows = process . platform === 'win32' ;
135162const winSepRegEx = / \/ / g;
@@ -152,7 +179,12 @@ translators.set('commonjs', async function commonjsStrategy(url, isMain) {
152179 exports = asyncESM . ESMLoader . cjsCache . get ( module ) ;
153180 asyncESM . ESMLoader . cjsCache . delete ( module ) ;
154181 } else {
155- exports = CJSModule . _load ( filename , undefined , isMain ) ;
182+ try {
183+ exports = CJSModule . _load ( filename , undefined , isMain ) ;
184+ } catch ( err ) {
185+ enrichCJSError ( err ) ;
186+ throw err ;
187+ }
156188 }
157189
158190 for ( const exportName of exportNames ) {
@@ -190,7 +222,13 @@ function cjsPreparseModuleExports(filename) {
190222 source = readFileSync ( filename , 'utf8' ) ;
191223 } catch { }
192224
193- const { exports, reexports } = cjsParse ( source || '' ) ;
225+ let exports , reexports ;
226+ try {
227+ ( { exports, reexports } = cjsParse ( source || '' ) ) ;
228+ } catch {
229+ exports = [ ] ;
230+ reexports = [ ] ;
231+ }
194232
195233 const exportNames = new SafeSet ( exports ) ;
196234
0 commit comments