Skip to content

Commit db6cd73

Browse files
authored
perf: reduce the amount of dynamic imports (#8465)
1 parent cc98c61 commit db6cd73

File tree

17 files changed

+225
-134
lines changed

17 files changed

+225
-134
lines changed

packages/vitest/src/integrations/chai/index.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
} from '@vitest/expect'
1212
import { getCurrentTest } from '@vitest/runner'
1313
import { getTestName } from '@vitest/runner/utils'
14-
import { getCurrentEnvironment, getWorkerState } from '../../runtime/utils'
14+
import { getWorkerState } from '../../runtime/utils'
1515
import { createExpectPoll } from './poll'
1616
import './setup'
1717

@@ -47,7 +47,6 @@ export function createExpect(test?: TaskPopulated): ExpectStatic {
4747
isExpectingAssertionsError: null,
4848
expectedAssertionsNumber: null,
4949
expectedAssertionsNumberErrorGen: null,
50-
environment: getCurrentEnvironment(),
5150
get testPath() {
5251
return getWorkerState().filepath
5352
},

packages/vitest/src/integrations/vi.ts

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -422,23 +422,22 @@ export interface VitestUtils {
422422
setConfig: (config: RuntimeOptions) => void
423423

424424
/**
425-
* If config was changed with `vi.setConfig`, this will reset it to the original state.
425+
* If config was changed with `vi.setConfig`, this will reset it to the original state().
426426
*/
427427
resetConfig: () => void
428428
}
429429

430430
function createVitest(): VitestUtils {
431-
let _mockedDate: Date | null = null
432431
let _config: null | SerializedConfig = null
433432

434-
const workerState = getWorkerState()
433+
const state = () => getWorkerState()
435434

436435
let _timers: FakeTimers
437436

438437
const timers = () =>
439438
(_timers ||= new FakeTimers({
440439
global: globalThis,
441-
config: workerState.config.fakeTimers,
440+
config: state().config.fakeTimers,
442441
}))
443442

444443
const _stubsGlobal = new Map<
@@ -454,7 +453,7 @@ function createVitest(): VitestUtils {
454453
if (isChildProcess()) {
455454
if (
456455
config?.toFake?.includes('nextTick')
457-
|| workerState.config?.fakeTimers?.toFake?.includes('nextTick')
456+
|| state().config?.fakeTimers?.toFake?.includes('nextTick')
458457
) {
459458
throw new Error(
460459
'vi.useFakeTimers({ toFake: ["nextTick"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.',
@@ -463,10 +462,10 @@ function createVitest(): VitestUtils {
463462
}
464463

465464
if (config) {
466-
timers().configure({ ...workerState.config.fakeTimers, ...config })
465+
timers().configure({ ...state().config.fakeTimers, ...config })
467466
}
468467
else {
469-
timers().configure(workerState.config.fakeTimers)
468+
timers().configure(state().config.fakeTimers)
470469
}
471470

472471
timers().useFakeTimers()
@@ -479,7 +478,6 @@ function createVitest(): VitestUtils {
479478

480479
useRealTimers() {
481480
timers().useRealTimers()
482-
_mockedDate = null
483481
return utils
484482
},
485483

@@ -687,8 +685,7 @@ function createVitest(): VitestUtils {
687685
},
688686

689687
stubEnv(name: string, value: string | boolean | undefined) {
690-
const state = getWorkerState()
691-
const env = state.metaEnv
688+
const env = state().metaEnv
692689
if (!_stubsEnv.has(name)) {
693690
_stubsEnv.set(name, env[name])
694691
}
@@ -718,8 +715,7 @@ function createVitest(): VitestUtils {
718715
},
719716

720717
unstubAllEnvs() {
721-
const state = getWorkerState()
722-
const env = state.metaEnv
718+
const env = state().metaEnv
723719
_stubsEnv.forEach((original, name) => {
724720
if (original === undefined) {
725721
delete env[name]
@@ -733,7 +729,7 @@ function createVitest(): VitestUtils {
733729
},
734730

735731
resetModules() {
736-
resetModules(workerState.evaluatedModules)
732+
resetModules(state().evaluatedModules)
737733
return utils
738734
},
739735

@@ -743,14 +739,14 @@ function createVitest(): VitestUtils {
743739

744740
setConfig(config: RuntimeOptions) {
745741
if (!_config) {
746-
_config = { ...workerState.config }
742+
_config = { ...state().config }
747743
}
748-
Object.assign(workerState.config, config)
744+
Object.assign(state().config, config)
749745
},
750746

751747
resetConfig() {
752748
if (_config) {
753-
Object.assign(workerState.config, _config)
749+
Object.assign(state().config, _config)
754750
}
755751
},
756752
}

packages/vitest/src/node/config/serializeConfig.ts

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
1-
import type { ResolvedConfig as ViteConfig } from 'vite'
2-
import type { ResolvedConfig, SerializedConfig } from '../types/config'
1+
import type { TestProject } from '../project'
2+
import type { SerializedConfig } from '../types/config'
33

4-
export function serializeConfig(
5-
config: ResolvedConfig,
6-
coreConfig: ResolvedConfig,
7-
viteConfig: ViteConfig | undefined,
8-
): SerializedConfig {
4+
export function serializeConfig(project: TestProject): SerializedConfig {
5+
const { config, globalConfig } = project
6+
const viteConfig = project._vite?.config
97
const optimizer = config.deps?.optimizer || {}
108
const poolOptions = config.poolOptions
119

@@ -69,35 +67,35 @@ export function serializeConfig(
6967
forks: {
7068
singleFork:
7169
poolOptions?.forks?.singleFork
72-
?? coreConfig.poolOptions?.forks?.singleFork
70+
?? globalConfig.poolOptions?.forks?.singleFork
7371
?? false,
7472
isolate:
7573
poolOptions?.forks?.isolate
7674
?? isolate
77-
?? coreConfig.poolOptions?.forks?.isolate
75+
?? globalConfig.poolOptions?.forks?.isolate
7876
?? true,
7977
},
8078
threads: {
8179
singleThread:
8280
poolOptions?.threads?.singleThread
83-
?? coreConfig.poolOptions?.threads?.singleThread
81+
?? globalConfig.poolOptions?.threads?.singleThread
8482
?? false,
8583
isolate:
8684
poolOptions?.threads?.isolate
8785
?? isolate
88-
?? coreConfig.poolOptions?.threads?.isolate
86+
?? globalConfig.poolOptions?.threads?.isolate
8987
?? true,
9088
},
9189
vmThreads: {
9290
singleThread:
9391
poolOptions?.vmThreads?.singleThread
94-
?? coreConfig.poolOptions?.vmThreads?.singleThread
92+
?? globalConfig.poolOptions?.vmThreads?.singleThread
9593
?? false,
9694
},
9795
vmForks: {
9896
singleFork:
9997
poolOptions?.vmForks?.singleFork
100-
?? coreConfig.poolOptions?.vmForks?.singleFork
98+
?? globalConfig.poolOptions?.vmForks?.singleFork
10199
?? false,
102100
},
103101
},
@@ -113,28 +111,28 @@ export function serializeConfig(
113111
snapshotOptions: {
114112
// TODO: store it differently, not on the config
115113
snapshotEnvironment: undefined!,
116-
updateSnapshot: coreConfig.snapshotOptions.updateSnapshot,
114+
updateSnapshot: globalConfig.snapshotOptions.updateSnapshot,
117115
snapshotFormat: {
118-
...coreConfig.snapshotOptions.snapshotFormat,
116+
...globalConfig.snapshotOptions.snapshotFormat,
119117
},
120118
expand:
121119
config.snapshotOptions.expand
122-
?? coreConfig.snapshotOptions.expand,
120+
?? globalConfig.snapshotOptions.expand,
123121
},
124122
sequence: {
125-
shuffle: coreConfig.sequence.shuffle,
126-
concurrent: coreConfig.sequence.concurrent,
127-
seed: coreConfig.sequence.seed,
128-
hooks: coreConfig.sequence.hooks,
129-
setupFiles: coreConfig.sequence.setupFiles,
123+
shuffle: globalConfig.sequence.shuffle,
124+
concurrent: globalConfig.sequence.concurrent,
125+
seed: globalConfig.sequence.seed,
126+
hooks: globalConfig.sequence.hooks,
127+
setupFiles: globalConfig.sequence.setupFiles,
130128
},
131-
inspect: coreConfig.inspect,
132-
inspectBrk: coreConfig.inspectBrk,
133-
inspector: coreConfig.inspector,
129+
inspect: globalConfig.inspect,
130+
inspectBrk: globalConfig.inspectBrk,
131+
inspector: globalConfig.inspector,
134132
watch: config.watch,
135133
includeTaskLocation:
136134
config.includeTaskLocation
137-
?? coreConfig.includeTaskLocation,
135+
?? globalConfig.includeTaskLocation,
138136
env: {
139137
...viteConfig?.env,
140138
...config.env,
@@ -161,9 +159,13 @@ export function serializeConfig(
161159
})(config.browser),
162160
standalone: config.standalone,
163161
printConsoleTrace:
164-
config.printConsoleTrace ?? coreConfig.printConsoleTrace,
162+
config.printConsoleTrace ?? globalConfig.printConsoleTrace,
165163
benchmark: config.benchmark && {
166164
includeSamples: config.benchmark.includeSamples,
167165
},
166+
// the browser initialized them via `@vite/env` import
167+
serializedDefines: config.browser.enabled
168+
? ''
169+
: project._serializedDefines || '',
168170
}
169171
}

packages/vitest/src/node/project.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { isAbsolute, join, relative } from 'pathe'
2222
import pm from 'picomatch'
2323
import { glob } from 'tinyglobby'
2424
import { setup } from '../api/setup'
25+
import { createDefinesScript } from '../utils/config-helpers'
2526
import { isBrowserEnabled, resolveConfig } from './config/resolveConfig'
2627
import { serializeConfig } from './config/serializeConfig'
2728
import { ServerModuleRunner } from './environments/serverRunner'
@@ -62,6 +63,7 @@ export class TestProject {
6263
/** @internal */ _vite?: ViteDevServer
6364
/** @internal */ _hash?: string
6465
/** @internal */ _resolver!: VitestResolver
66+
/** @internal */ _serializedDefines?: string
6567
/** @inetrnal */ testFilesList: string[] | null = null
6668

6769
private runner!: ModuleRunner
@@ -555,6 +557,7 @@ export class TestProject {
555557

556558
this._resolver = new VitestResolver(server.config.cacheDir, this._config)
557559
this._vite = server
560+
this._serializedDefines = createDefinesScript(server.config.define)
558561

559562
const environment = server.environments.__vitest__
560563
this.runner = new ServerModuleRunner(
@@ -566,11 +569,7 @@ export class TestProject {
566569

567570
private _serializeOverriddenConfig(): SerializedConfig {
568571
// TODO: serialize the config _once_ or when needed
569-
const config = serializeConfig(
570-
this.config,
571-
this.vitest.config,
572-
this.vite.config,
573-
)
572+
const config = serializeConfig(this)
574573
if (!this.vitest.configOverride) {
575574
return config
576575
}
@@ -619,6 +618,7 @@ export class TestProject {
619618
project._vite = vitest.vite
620619
project._config = vitest.config
621620
project._resolver = vitest._resolver
621+
project._serializedDefines = createDefinesScript(vitest.vite.config.define)
622622
project._setHash()
623623
project._provideObject(vitest.config.provide)
624624
return project
@@ -633,6 +633,7 @@ export class TestProject {
633633
clone._config = config
634634
clone._setHash()
635635
clone._parent = parent
636+
clone._serializedDefines = parent._serializedDefines
636637
clone._provideObject(config.provide)
637638
return clone
638639
}

packages/vitest/src/runtime/config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ export interface SerializedConfig {
130130
benchmark: {
131131
includeSamples: boolean
132132
} | undefined
133+
serializedDefines: string
133134
}
134135

135136
export interface SerializedCoverageConfig {

packages/vitest/src/runtime/moduleRunner/moduleMocker.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ interface MockContext {
2020

2121
export interface VitestMockerOptions {
2222
context?: vm.Context
23-
23+
spyModule?: typeof import('@vitest/spy')
2424
root: string
2525
moduleDirectories: string[]
2626
resolveId: (id: string, importer?: string) => Promise<{
@@ -72,6 +72,10 @@ export class VitestMocker {
7272
}
7373
}
7474

75+
if (options.spyModule) {
76+
this.spyModule = options.spyModule
77+
}
78+
7579
const Symbol = this.primitives.Symbol
7680

7781
this.filterPublicKeys = [

packages/vitest/src/runtime/moduleRunner/moduleRunner.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export class VitestModuleRunner extends ModuleRunner {
2929
)
3030
this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo
3131
this.mocker = options.mocker || new VitestMocker(this, {
32+
spyModule: options.spyModule,
3233
context: options.vm?.context,
3334
resolveId: options.transport.resolveId,
3435
get root() {
@@ -143,6 +144,7 @@ export interface VitestModuleRunnerOptions {
143144
getWorkerState: () => WorkerGlobalState
144145
mocker?: VitestMocker
145146
vm?: VitestVmOptions
147+
spyModule?: typeof import('@vitest/spy')
146148
}
147149

148150
export interface VitestVmOptions {

packages/vitest/src/runtime/moduleRunner/startModuleRunner.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,13 @@ export interface ContextModuleRunnerOptions {
2525
context?: vm.Context
2626
externalModulesExecutor?: ExternalModulesExecutor
2727
state: WorkerGlobalState
28+
spyModule?: typeof import('@vitest/spy')
2829
}
2930

3031
const cwd = process.cwd()
3132
const isWindows = process.platform === 'win32'
3233

33-
export async function startVitestModuleRunner(options: ContextModuleRunnerOptions): Promise<VitestModuleRunner> {
34+
export function startVitestModuleRunner(options: ContextModuleRunnerOptions): VitestModuleRunner {
3435
const state = (): WorkerGlobalState =>
3536
// @ts-expect-error injected untyped global
3637
globalThis.__vitest_worker__ || options.state
@@ -68,6 +69,7 @@ export async function startVitestModuleRunner(options: ContextModuleRunnerOption
6869
)
6970

7071
const moduleRunner: VitestModuleRunner = new VitestModuleRunner({
72+
spyModule: options.spyModule,
7173
evaluatedModules: options.evaluatedModules,
7274
evaluator,
7375
mocker: options.mocker,
@@ -161,8 +163,8 @@ export async function startVitestModuleRunner(options: ContextModuleRunnerOption
161163
vm,
162164
})
163165

164-
await moduleRunner.import('/@vite/env')
165-
await moduleRunner.mocker.initializeSpyModule()
166+
// await moduleRunner.import('/@vite/env')
167+
// await moduleRunner.mocker.initializeSpyModule()
166168

167169
return moduleRunner
168170
}

packages/vitest/src/runtime/runVmTests.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ export async function run(
3636
})
3737

3838
const viteEnvironment = workerState.environment.viteEnvironment || workerState.environment.name
39+
VitestIndex.expect.setState({
40+
environment: workerState.environment.name,
41+
})
3942
if (viteEnvironment === 'client') {
4043
const _require = createRequire(import.meta.url)
4144
// always mock "required" `css` files, because we cannot process them

0 commit comments

Comments
 (0)