@@ -9,6 +9,7 @@ import { extractSourceMap } from './source-map'
99import {
1010 cleanUrl ,
1111 createImportMetaEnvProxy ,
12+ isBareImport ,
1213 isInternalRequest ,
1314 isNodeBuiltin ,
1415 isPrimitive ,
@@ -325,6 +326,28 @@ export class ViteNodeRunner {
325326 return await this . cachedRequest ( id , fsPath , callstack )
326327 }
327328
329+ private async _fetchModule ( id : string , importer ?: string ) {
330+ try {
331+ return await this . options . fetchModule ( id )
332+ }
333+ catch ( cause : any ) {
334+ // rethrow vite error if it cannot load the module because it's not resolved
335+ if (
336+ ( typeof cause === 'object' && cause . code === 'ERR_LOAD_URL' )
337+ || ( typeof cause ?. message === 'string' && cause . message . includes ( 'Failed to load url' ) )
338+ ) {
339+ const error = new Error (
340+ `Cannot find ${ isBareImport ( id ) ? 'package' : 'module' } '${ id } '${ importer ? ` imported from '${ importer } '` : '' } ` ,
341+ { cause } ,
342+ ) as Error & { code : string }
343+ error . code = 'ERR_MODULE_NOT_FOUND'
344+ throw error
345+ }
346+
347+ throw cause
348+ }
349+ }
350+
328351 /** @internal */
329352 async directRequest ( id : string , fsPath : string , _callstack : string [ ] ) {
330353 const moduleId = normalizeModuleId ( fsPath )
@@ -345,7 +368,10 @@ export class ViteNodeRunner {
345368 if ( id in requestStubs ) {
346369 return requestStubs [ id ]
347370 }
348- let { code : transformed , externalize } = await this . options . fetchModule ( id )
371+ let { code : transformed , externalize } = await this . _fetchModule (
372+ id ,
373+ callstack [ callstack . length - 2 ] ,
374+ )
349375
350376 if ( externalize ) {
351377 debugNative ( externalize )
0 commit comments