@@ -47,20 +47,11 @@ async function importLocalModule<T extends object>(identifier: string, modulePat
4747 const dotIndex = modulePath . lastIndexOf ( '.' ) ;
4848 const extension = dotIndex === - 1 ? undefined : modulePath . slice ( dotIndex ) ;
4949 const modulePromise = extension === '.json' ? import ( modulePath , { with : { type : 'json' } } ) : import ( modulePath ) ;
50-
51- try {
52- return ( await modulePromise ) as unknown as T ;
53- } catch ( error ) {
54- throw new Error ( `Failed to import ${ identifier } at "${ modulePath } " as a local module` , { cause : error } ) ;
55- }
50+ return await handleImportPromise ( modulePromise , identifier , modulePath ) ;
5651}
5752
5853async function importExternalModule < T extends object > ( identifier : string , modulePath : string ) : Promise < T > {
59- try {
60- return ( await import ( modulePath ) ) as unknown as T ;
61- } catch ( error ) {
62- throw new Error ( `Failed to import ${ identifier } at "${ modulePath } " as a module` , { cause : error } ) ;
63- }
54+ return await handleImportPromise ( import ( modulePath ) , identifier , modulePath ) ;
6455}
6556
6657async function importExternalUserModule < T extends object > ( identifier : string , modulePath : string ) : Promise < T > {
@@ -69,3 +60,22 @@ async function importExternalUserModule<T extends object>(identifier: string, mo
6960 const userModulePath = userRequire . resolve ( modulePath ) ;
7061 return await importExternalModule < T > ( identifier , userModulePath ) ;
7162}
63+
64+ async function handleImportPromise < T extends object > (
65+ importPromise : Promise < unknown > ,
66+ identifier : string ,
67+ modulePath : string ,
68+ ) : Promise < T > {
69+ try {
70+ return ( await importPromise ) as T ;
71+ } catch ( error ) {
72+ let causeMessage =
73+ ! ! error && typeof error === 'object' && 'message' in error && typeof error . message === 'string'
74+ ? ( error as { message : string } ) . message
75+ : undefined ;
76+ causeMessage = causeMessage ? ` (caused by: ${ causeMessage } )` : '' ;
77+ throw new Error ( `Failed to import ${ identifier } at "${ modulePath } " as a module${ causeMessage } ` , {
78+ cause : error ,
79+ } ) ;
80+ }
81+ }
0 commit comments