diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index c8f2c8d88fdacd..eafde8c25b67d1 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -19,11 +19,7 @@ interface SourceMapLike { sourceRoot?: string } -export async function injectSourcesContent( - map: SourceMapLike, - file: string, - logger: Logger, -): Promise { +async function computeSourceRoute(map: SourceMapLike, file: string) { let sourceRoot: string | undefined try { // The source root is undefined for virtual modules and permission errors. @@ -31,28 +27,48 @@ export async function injectSourcesContent( path.resolve(path.dirname(file), map.sourceRoot || ''), ) } catch {} + return sourceRoot +} + +export async function injectSourcesContent( + map: SourceMapLike, + file: string, + logger: Logger, +): Promise { + let sourceRootPromise: Promise const missingSources: string[] = [] const sourcesContent = map.sourcesContent || [] - await Promise.all( - map.sources.map(async (sourcePath, index) => { - let content = null - if (sourcePath && !virtualSourceRE.test(sourcePath)) { - sourcePath = decodeURI(sourcePath) - if (sourceRoot) { - sourcePath = path.resolve(sourceRoot, sourcePath) - } - // inject content from source file when sourcesContent is null - content = - sourcesContent[index] ?? - (await fsp.readFile(sourcePath, 'utf-8').catch(() => { - missingSources.push(sourcePath) - return null - })) - } - sourcesContent[index] = content - }), - ) + const sourcesContentPromises: Promise[] = [] + for (let index = 0; index < map.sources.length; index++) { + const sourcePath = map.sources[index] + if ( + !sourcesContent[index] && + sourcePath && + !virtualSourceRE.test(sourcePath) + ) { + sourcesContentPromises.push( + (async () => { + // inject content from source file when sourcesContent is null + sourceRootPromise ??= computeSourceRoute(map, file) + const sourceRoot = await sourceRootPromise + let resolvedSourcePath = decodeURI(sourcePath) + if (sourceRoot) { + resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath) + } + + sourcesContent[index] = await fsp + .readFile(resolvedSourcePath, 'utf-8') + .catch(() => { + missingSources.push(resolvedSourcePath) + return null + }) + })(), + ) + } + } + + await Promise.all(sourcesContentPromises) map.sourcesContent = sourcesContent