/
workspace.ts
175 lines (162 loc) · 6.22 KB
/
workspace.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
import { builtinModules } from 'node:module'
import { dirname, relative } from 'pathe'
import type { UserConfig as ViteConfig, Plugin as VitePlugin } from 'vite'
import { version as viteVersion } from 'vite'
import { configDefaults } from '../../defaults'
import { generateScopedClassName } from '../../integrations/css/css-modules'
import { deepMerge } from '../../utils/base'
import type { WorkspaceProject } from '../workspace'
import type { UserWorkspaceConfig } from '../../types'
import { CoverageTransform } from './coverageTransform'
import { CSSEnablerPlugin } from './cssEnabler'
import { EnvReplacerPlugin } from './envReplacer'
import { GlobalSetupPlugin } from './globalSetup'
import { MocksPlugin } from './mocks'
interface WorkspaceOptions extends UserWorkspaceConfig {
root?: string
workspacePath: string | number
}
export function WorkspaceVitestPlugin(project: WorkspaceProject, options: WorkspaceOptions) {
return <VitePlugin[]>[
{
name: 'vitest:project',
enforce: 'pre',
options() {
this.meta.watchMode = false
},
// TODO: refactor so we don't have the same code here and in plugins/index.ts
config(viteConfig) {
if (viteConfig.define) {
delete viteConfig.define['import.meta.vitest']
delete viteConfig.define['process.env']
}
const env: Record<string, any> = {}
for (const key in viteConfig.define) {
const val = viteConfig.define[key]
let replacement: any
try {
replacement = typeof val === 'string' ? JSON.parse(val) : val
}
catch {
// probably means it contains reference to some variable,
// like this: "__VAR__": "process.env.VAR"
continue
}
if (key.startsWith('import.meta.env.')) {
const envKey = key.slice('import.meta.env.'.length)
env[envKey] = replacement
delete viteConfig.define[key]
}
else if (key.startsWith('process.env.')) {
const envKey = key.slice('process.env.'.length)
env[envKey] = replacement
delete viteConfig.define[key]
}
}
const testConfig = viteConfig.test || {}
const root = testConfig.root || viteConfig.root || options.root
let name = testConfig.name
if (!name) {
if (typeof options.workspacePath === 'string')
name = dirname(options.workspacePath).split('/').pop()
else
name = options.workspacePath.toString()
}
const config: ViteConfig = {
root,
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,
},
esbuild: {
sourcemap: 'external',
// Enables using ignore hint for coverage providers with @preserve keyword
legalComments: 'inline',
},
server: {
// disable watch mode in workspaces,
// because it is handled by the top-level watcher
watch: {
ignored: ['**/*'],
depth: 0,
persistent: false,
},
open: false,
hmr: false,
preTransformRequests: false,
},
test: {
env,
name,
},
}
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 = project.config.root
return generateScopedClassName(classNameStrategy, name, relative(root, filename))!
}
}
}
const optimizeConfig: Partial<ViteConfig> = {}
const optimizer = testConfig.deps?.experimentalOptimizer
const [major, minor] = viteVersion.split('.').map(Number)
const allowed = major >= 5 || (major === 4 && minor >= 3)
if (!allowed && optimizer?.enabled === true)
console.warn(`Vitest: "deps.experimentalOptimizer" is only available in Vite >= 4.3.0, current Vite version: ${viteVersion}`)
if (!allowed || optimizer?.enabled !== true) {
optimizeConfig.cacheDir = undefined
optimizeConfig.optimizeDeps = {
// experimental in Vite >2.9.2, entries remains to help with older versions
disabled: true,
entries: [],
}
}
else {
const cacheDir = testConfig.cache !== false ? testConfig.cache?.dir : null
optimizeConfig.cacheDir = cacheDir ?? 'node_modules/.vitest'
optimizeConfig.optimizeDeps = {
...viteConfig.optimizeDeps,
...optimizer,
noDiscovery: true,
disabled: false,
entries: [],
exclude: ['vitest', ...builtinModules, ...(optimizer.exclude || viteConfig.optimizeDeps?.exclude || [])],
include: (optimizer.include || viteConfig.optimizeDeps?.include || []).filter((n: string) => n !== 'vitest'),
}
}
Object.assign(config, optimizeConfig)
return config
},
async configureServer(server) {
try {
const options = deepMerge(
{},
configDefaults,
server.config.test || {},
)
await project.setServer(options, server)
}
catch (err) {
await project.ctx.logger.printError(err, true)
process.exit(1)
}
await server.watcher.close()
},
},
EnvReplacerPlugin(),
...CSSEnablerPlugin(project),
CoverageTransform(project.ctx),
GlobalSetupPlugin(project, project.ctx.logger),
MocksPlugin(),
]
}