Skip to content

Commit

Permalink
fix(module-runner): delay function eval until module runner instantia…
Browse files Browse the repository at this point in the history
…tion (#18480)
  • Loading branch information
hi-ogawa authored Oct 28, 2024
1 parent 915cd7f commit 472afbd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/module-runner/esmEvaluator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
AsyncFunction,
asyncFunctionDeclarationPaddingLineCount,
getAsyncFunctionDeclarationPaddingLineCount,
} from '../shared/utils'
import {
ssrDynamicImportKey,
Expand All @@ -12,7 +12,7 @@ import {
import type { ModuleEvaluator, ModuleRunnerContext } from './types'

export class ESModulesEvaluator implements ModuleEvaluator {
startOffset = asyncFunctionDeclarationPaddingLineCount
startOffset = getAsyncFunctionDeclarationPaddingLineCount()

async runInlinedModule(
context: ModuleRunnerContext,
Expand Down
13 changes: 9 additions & 4 deletions packages/vite/src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,14 @@ export function withTrailingSlash(path: string): string {
export const AsyncFunction = async function () {}.constructor as typeof Function

// https://github.com/nodejs/node/issues/43047#issuecomment-1564068099
export const asyncFunctionDeclarationPaddingLineCount =
/** #__PURE__ */ (() => {
let asyncFunctionDeclarationPaddingLineCount: number | undefined

export function getAsyncFunctionDeclarationPaddingLineCount(): number {
if (typeof asyncFunctionDeclarationPaddingLineCount === 'undefined') {
const body = '/*code*/'
const source = new AsyncFunction('a', 'b', body).toString()
return source.slice(0, source.indexOf(body)).split('\n').length - 1
})()
asyncFunctionDeclarationPaddingLineCount =
source.slice(0, source.indexOf(body)).split('\n').length - 1
}
return asyncFunctionDeclarationPaddingLineCount
}

0 comments on commit 472afbd

Please sign in to comment.