11import { pathToFileURL } from 'node:url'
22import vm from 'node:vm'
33import { DEFAULT_REQUEST_STUBS , ModuleCacheMap , ViteNodeRunner } from 'vite-node/client'
4- import { isInternalRequest , isNodeBuiltin , isPrimitive } from 'vite-node/utils'
4+ import { isInternalRequest , isNodeBuiltin , isPrimitive , toFilePath } from 'vite-node/utils'
55import type { ViteNodeRunnerOptions } from 'vite-node'
66import { normalize , relative , resolve } from 'pathe'
77import { processError } from '@vitest/utils/error'
@@ -41,6 +41,7 @@ export const packageCache = new Map<string, any>()
4141export const moduleCache = new ModuleCacheMap ( )
4242export const mockMap : MockMap = new Map ( )
4343export const fileMap = new FileMap ( )
44+ const externalizeMap = new Map < string , string > ( )
4445
4546export async function startViteNode ( options : ContextExecutorOptions ) {
4647 if ( _viteNode )
@@ -64,7 +65,7 @@ export interface ContextExecutorOptions {
6465
6566export async function startVitestExecutor ( options : ContextExecutorOptions ) {
6667 // @ts -expect-error injected untyped global
67- const state = ( ) => globalThis . __vitest_worker__ || options . state
68+ const state = ( ) : WorkerGlobalState => globalThis . __vitest_worker__ || options . state
6869 const rpc = ( ) => state ( ) . rpc
6970
7071 const processExit = process . exit
@@ -97,7 +98,18 @@ export async function startVitestExecutor(options: ContextExecutorOptions) {
9798 }
9899
99100 return await createVitestExecutor ( {
100- fetchModule ( id ) {
101+ async fetchModule ( id ) {
102+ if ( externalizeMap . has ( id ) )
103+ return { externalize : externalizeMap . get ( id ) ! }
104+ // always externalize Vitest because we import from there before running tests
105+ // so we already have it cached by Node.js
106+ if ( id . includes ( distDir ) ) {
107+ const { path } = toFilePath ( id , state ( ) . config . root )
108+ const externalize = pathToFileURL ( path ) . toString ( )
109+ externalizeMap . set ( id , externalize )
110+ return { externalize }
111+ }
112+
101113 return rpc ( ) . fetch ( id , getTransformMode ( ) )
102114 } ,
103115 resolveId ( id , importer ) {
0 commit comments