/
index.ts
183 lines (160 loc) · 6.53 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
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 } from '../../utils'
import { ensurePackageInstalled } from '../pkg'
import { resolveApiServerConfig } from '../config'
import { Vitest } from '../core'
import { generateScopedClassName } from '../../integrations/css/css-modules'
import { SsrReplacerPlugin } from './ssrReplacer'
import { GlobalSetupPlugin } from './globalSetup'
import { CSSEnablerPlugin } from './cssEnabler'
import { CoverageTransform } from './coverageTransform'
import { MocksPlugin } from './mocks'
import { deleteDefineConfig, resolveOptimizerConfig } from './utils'
import { VitestResolver } from './vitestResolver'
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 ensurePackageInstalled('@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)
// 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
if (testConfig.ui && testConfig.open)
open = testConfig.uiBase ?? '/__vitest__/'
const config: ViteConfig = {
root: viteConfig.test?.root || options.root,
esbuild: {
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'],
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore we support Vite ^3.0, but browserField is available in Vite ^3.2
browserField: false,
},
server: {
...testConfig.api,
watch: {
ignored: testConfig.watchExclude,
},
open,
hmr: false,
preTransformRequests: 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))!
}
}
}
const webOptimizer = resolveOptimizerConfig(testConfig.deps?.experimentalOptimizer?.web, viteConfig.optimizeDeps, testConfig)
const ssrOptimizer = resolveOptimizerConfig(testConfig.deps?.experimentalOptimizer?.ssr, viteConfig.ssr?.optimizeDeps, testConfig)
config.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || config.cacheDir
config.optimizeDeps = webOptimizer.optimizeDeps
config.ssr = {
optimizeDeps: ssrOptimizer.optimizeDeps,
}
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' : ''
process.env.SSR ??= '1'
for (const name in envs)
process.env[name] ??= envs[name]
// don't watch files in run mode
if (!options.watch) {
viteConfig.server.watch = {
persistent: false,
depth: 0,
ignored: ['**/*'],
}
}
},
async configureServer(server) {
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, 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(),
GlobalSetupPlugin(ctx, ctx.logger),
...CSSEnablerPlugin(ctx),
CoverageTransform(ctx),
options.ui
? await UIPlugin()
: null,
MocksPlugin(),
VitestResolver(ctx),
]
.filter(notNullish)
}