diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index 16e51e287db3a7..07e6a5c39c444c 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -634,13 +634,22 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin { ) .join(',')}]` - s.append(`\ + const mapDepsCode = `\ function __vite__mapDeps(indexes) { if (!__vite__mapDeps.viteFileDeps) { __vite__mapDeps.viteFileDeps = ${fileDepsCode} } return indexes.map((i) => __vite__mapDeps.viteFileDeps[i]) -}`) +}\n` + + // inject extra code before sourcemap comment + const mapFileCommentMatch = + convertSourceMap.mapFileCommentRegex.exec(code) + if (mapFileCommentMatch) { + s.appendRight(mapFileCommentMatch.index, mapDepsCode) + } else { + s.append(mapDepsCode) + } // there may still be markers due to inlined dynamic imports, remove // all the markers regardless diff --git a/playground/js-sourcemap/__tests__/js-sourcemap.spec.ts b/playground/js-sourcemap/__tests__/js-sourcemap.spec.ts index d4e6888ab5edd8..da1a517ca25beb 100644 --- a/playground/js-sourcemap/__tests__/js-sourcemap.spec.ts +++ b/playground/js-sourcemap/__tests__/js-sourcemap.spec.ts @@ -129,5 +129,10 @@ describe.runIf(isBuild)('build tests', () => { "version": 3, } `) + // + const js = findAssetFile(/after-preload-dynamic.*\.js$/) + expect(js.trim().split('\n').at(-1)).toMatch( + /^\/\/# sourceMappingURL=after-preload-dynamic.*\.js\.map$/, + ) }) })