-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.ts
214 lines (189 loc) · 7.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import type { UserConfig as ViteConfig, Plugin as VitePlugin } from 'vite'
import { relative } from 'pathe'
import { configDefaults } from '../../defaults'
import type { ResolvedConfig, UserConfig } from '../../types'
import { deepMerge, notNullish, removeUndefinedValues, toArray } from '../../utils'
import { resolveApiServerConfig } from '../config'
import { Vitest } from '../core'
import { generateScopedClassName } from '../../integrations/css/css-modules'
import { SsrReplacerPlugin } from './ssrReplacer'
import { CSSEnablerPlugin } from './cssEnabler'
import { CoverageTransform } from './coverageTransform'
import { MocksPlugin } from './mocks'
import { deleteDefineConfig, hijackVitePluginInject, resolveFsAllow } from './utils'
import { VitestResolver } from './vitestResolver'
import { VitestOptimizer } from './optimizer'
import { NormalizeURLPlugin } from './normalizeURL'
export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest('test')): Promise<VitePlugin[]> {
const userConfig = deepMerge({}, options) as UserConfig
const getRoot = () => ctx.config?.root || options.root || process.cwd()
async function UIPlugin() {
await ctx.packageInstaller.ensureInstalled('@vitest/ui', getRoot())
return (await import('@vitest/ui')).default(ctx)
}
return [
<VitePlugin>{
name: 'vitest',
enforce: 'pre',
options() {
this.meta.watchMode = false
},
async config(viteConfig) {
if (options.watch) {
// Earlier runs have overwritten values of the `options`.
// Reset it back to initial user config before setting up the server again.
options = deepMerge({}, userConfig) as UserConfig
}
// preliminary merge of options to be able to create server options for vite
// however to allow vitest plugins to modify vitest config values
// this is repeated in configResolved where the config is final
const testConfig = deepMerge(
{} as UserConfig,
configDefaults,
options,
removeUndefinedValues(viteConfig.test ?? {}),
)
testConfig.api = resolveApiServerConfig(testConfig)
testConfig.poolOptions ??= {}
testConfig.poolOptions.threads ??= {}
testConfig.poolOptions.forks ??= {}
// prefer --poolOptions.{name}.isolate CLI arguments over --isolate, but still respect config value
testConfig.poolOptions.threads.isolate = options.poolOptions?.threads?.isolate ?? options.isolate ?? testConfig.poolOptions.threads.isolate ?? viteConfig.test?.isolate
testConfig.poolOptions.forks.isolate = options.poolOptions?.forks?.isolate ?? options.isolate ?? testConfig.poolOptions.forks.isolate ?? viteConfig.test?.isolate
// store defines for globalThis to make them
// reassignable when running in worker in src/runtime/setup.ts
const defines: Record<string, any> = deleteDefineConfig(viteConfig)
;(options as ResolvedConfig).defines = defines
let open: string | boolean | undefined = false
if (testConfig.ui && testConfig.open)
open = testConfig.uiBase ?? '/__vitest__/'
const config: ViteConfig = {
root: viteConfig.test?.root || options.root,
esbuild: viteConfig.esbuild === false
? false
: {
sourcemap: 'external',
// Enables using ignore hint for coverage providers with @preserve keyword
legalComments: 'inline',
},
resolve: {
// by default Vite resolves `module` field, which not always a native ESM module
// setting this option can bypass that and fallback to cjs version
mainFields: [],
alias: testConfig.alias,
conditions: ['node'],
},
server: {
...testConfig.api,
watch: {
ignored: testConfig.watchExclude,
},
open,
hmr: false,
preTransformRequests: false,
fs: {
allow: resolveFsAllow(getRoot(), testConfig.config),
},
},
test: {
poolOptions: testConfig.poolOptions,
},
}
// we want inline dependencies to be resolved by analyser plugin so module graph is populated correctly
if (viteConfig.ssr?.noExternal !== true) {
const inline = testConfig.server?.deps?.inline
if (inline === true) {
config.ssr = { noExternal: true }
}
else {
const noExternal = viteConfig.ssr?.noExternal
const noExternalArray = typeof noExternal !== 'undefined' ? toArray(noExternal) : undefined
// filter the same packages
const uniqueInline = inline && noExternalArray
? inline.filter(dep => !noExternalArray.includes(dep))
: inline
config.ssr = {
noExternal: uniqueInline,
}
}
}
// chokidar fsevents is unstable on macos when emitting "ready" event
if (process.platform === 'darwin' && process.env.VITE_TEST_WATCHER_DEBUG) {
config.server!.watch!.useFsEvents = false
config.server!.watch!.usePolling = false
}
const classNameStrategy = (typeof testConfig.css !== 'boolean' && testConfig.css?.modules?.classNameStrategy) || 'stable'
if (classNameStrategy !== 'scoped') {
config.css ??= {}
config.css.modules ??= {}
if (config.css.modules) {
config.css.modules.generateScopedName = (name: string, filename: string) => {
const root = getRoot()
return generateScopedClassName(classNameStrategy, name, relative(root, filename))!
}
}
}
return config
},
async configResolved(viteConfig) {
const viteConfigTest = (viteConfig.test as any) || {}
if (viteConfigTest.watch === false)
viteConfigTest.run = true
if ('alias' in viteConfigTest)
delete viteConfigTest.alias
// viteConfig.test is final now, merge it for real
options = deepMerge(
{},
configDefaults,
viteConfigTest,
options,
)
options.api = resolveApiServerConfig(options)
// we replace every "import.meta.env" with "process.env"
// to allow reassigning, so we need to put all envs on process.env
const { PROD, DEV, ...envs } = viteConfig.env
// process.env can have only string values and will cast string on it if we pass other type,
// so we are making them truthy
process.env.PROD ??= PROD ? '1' : ''
process.env.DEV ??= DEV ? '1' : ''
for (const name in envs)
process.env[name] ??= envs[name]
// don't watch files in run mode
if (!options.watch)
viteConfig.server.watch = null
hijackVitePluginInject(viteConfig)
},
async configureServer(server) {
if (options.watch && process.env.VITE_TEST_WATCHER_DEBUG) {
server.watcher.on('ready', () => {
// eslint-disable-next-line no-console
console.log('[debug] watcher is ready')
})
}
try {
await ctx.setServer(options, server, userConfig)
if (options.api && options.watch)
(await import('../../api/setup')).setup(ctx)
}
catch (err) {
await ctx.logger.printError(err, { fullStack: true })
process.exit(1)
}
// #415, in run mode we don't need the watcher, close it would improve the performance
if (!options.watch)
await server.watcher.close()
},
},
SsrReplacerPlugin(),
...CSSEnablerPlugin(ctx),
CoverageTransform(ctx),
options.ui
? await UIPlugin()
: null,
MocksPlugin(),
VitestResolver(ctx),
VitestOptimizer(),
NormalizeURLPlugin(),
]
.filter(notNullish)
}