/
index.ts
105 lines (95 loc) · 2.84 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
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import { builtinModules } from 'node:module'
import { polyfillPath } from 'modern-node-polyfills'
import sirv from 'sirv'
import type { Plugin } from 'vite'
import { injectVitestModule } from './esmInjector'
const polyfills = [
'util',
]
// don't expose type to not bundle it here
export default (project: any, base = '/'): Plugin[] => {
const pkgRoot = resolve(fileURLToPath(import.meta.url), '../..')
const distRoot = resolve(pkgRoot, 'dist')
return [
{
enforce: 'pre',
name: 'vitest:browser',
async config(viteConfig) {
// Enables using ignore hint for coverage providers with @preserve keyword
viteConfig.esbuild ||= {}
viteConfig.esbuild.legalComments = 'inline'
},
async configureServer(server) {
server.middlewares.use(
base,
sirv(resolve(distRoot, 'client'), {
single: false,
dev: true,
}),
)
},
},
{
name: 'modern-node-polyfills',
enforce: 'pre',
config() {
return {
optimizeDeps: {
exclude: [
...polyfills,
...builtinModules,
'vitest',
'vitest/utils',
'vitest/browser',
'vitest/runners',
'@vitest/utils',
],
include: [
'@vitest/utils > concordance',
'@vitest/utils > loupe',
'@vitest/utils > pretty-format',
'vitest > chai',
],
},
}
},
async resolveId(id) {
if (!builtinModules.includes(id) && !polyfills.includes(id) && !id.startsWith('node:')) {
if (!/\?browserv=\w+$/.test(id))
return
let useId = id.slice(0, id.lastIndexOf('?'))
if (useId.startsWith('/@fs/'))
useId = useId.slice(5)
if (/^\w:/.test(useId))
useId = useId.replace(/\\/g, '/')
return useId
}
id = normalizeId(id)
return { id: await polyfillPath(id), moduleSideEffects: false }
},
},
{
name: 'vitest:browser:esm-injector',
enforce: 'post',
transform(source, id) {
const hijackESM = project.config.browser.slowHijackESM ?? false
if (!hijackESM)
return
return injectVitestModule(source, id, this.parse)
},
},
]
}
function normalizeId(id: string, base?: string): string {
if (base && id.startsWith(base))
id = `/${id.slice(base.length)}`
return id
.replace(/^\/@id\/__x00__/, '\0') // virtual modules start with `\0`
.replace(/^\/@id\//, '')
.replace(/^__vite-browser-external:/, '')
.replace(/^node:/, '')
.replace(/[?&]v=\w+/, '?') // remove ?v= query
.replace(/\?$/, '') // remove end query mark
}