Skip to content

Commit cba0805

Browse files
Vap0r1zesapphi-red
authored andcommitted
fix(ssr): load sourcemaps alongside modules (fix: vitejs#3288) (vitejs#11576)
1 parent 697dd00 commit cba0805

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

packages/vite/src/node/ssr/ssrModuleLoader.ts

+24-3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { transformRequest } from '../server/transformRequest'
1111
import type { InternalResolveOptionsWithOverrideConditions } from '../plugins/resolve'
1212
import { tryNodeResolve } from '../plugins/resolve'
13+
import { genSourceMapUrl } from '../server/sourcemap'
1314
import {
1415
ssrDynamicImportKey,
1516
ssrExportAllKey,
@@ -25,6 +26,16 @@ interface SSRContext {
2526

2627
type SSRModule = Record<string, any>
2728

29+
// eslint-disable-next-line @typescript-eslint/no-empty-function
30+
const AsyncFunction = async function () {}.constructor as typeof Function
31+
let fnDeclarationLineCount = 0
32+
{
33+
const body = '/*code*/'
34+
const source = new AsyncFunction('a', 'b', body).toString()
35+
fnDeclarationLineCount =
36+
source.slice(0, source.indexOf(body)).split('\n').length - 1
37+
}
38+
2839
const pendingModules = new Map<string, Promise<SSRModule>>()
2940
const pendingImports = new Map<string, string[]>()
3041

@@ -181,17 +192,27 @@ async function instantiateModule(
181192
}
182193
}
183194

195+
let sourceMapSuffix = ''
196+
if (result.map) {
197+
const moduleSourceMap = Object.assign({}, result.map, {
198+
// offset the first three lines of the module (function declaration and 'use strict')
199+
mappings: ';'.repeat(fnDeclarationLineCount + 1) + result.map.mappings,
200+
})
201+
sourceMapSuffix =
202+
'\n//# sourceMappingURL=' + genSourceMapUrl(moduleSourceMap)
203+
}
204+
184205
try {
185-
// eslint-disable-next-line @typescript-eslint/no-empty-function
186-
const AsyncFunction = async function () {}.constructor as typeof Function
187206
const initModule = new AsyncFunction(
188207
`global`,
189208
ssrModuleExportsKey,
190209
ssrImportMetaKey,
191210
ssrImportKey,
192211
ssrDynamicImportKey,
193212
ssrExportAllKey,
194-
'"use strict";' + result.code + `\n//# sourceURL=${mod.url}`,
213+
'"use strict";\n' +
214+
result.code +
215+
`\n//# sourceURL=${mod.url}${sourceMapSuffix}`,
195216
)
196217
await initModule(
197218
context.global,

0 commit comments

Comments
 (0)