diff --git a/packages/vite/src/node/ssr/ssrStacktrace.ts b/packages/vite/src/node/ssr/ssrStacktrace.ts index 5a2c55fdcc9830..a98af4dd94bb74 100644 --- a/packages/vite/src/node/ssr/ssrStacktrace.ts +++ b/packages/vite/src/node/ssr/ssrStacktrace.ts @@ -3,20 +3,28 @@ import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping' import type { ModuleGraph } from '../server/moduleGraph' let offset: number -try { - new Function('throw new Error(1)')() -} catch (e) { - // in Node 12, stack traces account for the function wrapper. - // in Node 13 and later, the function wrapper adds two lines, - // which must be subtracted to generate a valid mapping - const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]) - offset = match ? +match[1] - 1 : 0 + +function calculateOffsetOnce() { + if (offset !== undefined) { + return + } + + try { + new Function('throw new Error(1)')() + } catch (e) { + // in Node 12, stack traces account for the function wrapper. + // in Node 13 and later, the function wrapper adds two lines, + // which must be subtracted to generate a valid mapping + const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]) + offset = match ? +match[1] - 1 : 0 + } } export function ssrRewriteStacktrace( stack: string, moduleGraph: ModuleGraph, ): string { + calculateOffsetOnce() return stack .split('\n') .map((line) => {