/
index.ts
63 lines (57 loc) · 1.61 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
import { fileURLToPath } from 'url'
// eslint-disable-next-line no-restricted-imports
import { resolve } from 'path'
import { builtinModules } from 'module'
import { polyfillPath } from 'modern-node-polyfills'
import sirv from 'sirv'
import type { Plugin } from 'vite'
const polyfills = [
'util',
]
export default (base = '/'): Plugin[] => {
const pkgRoot = resolve(fileURLToPath(import.meta.url), '../..')
const distRoot = resolve(pkgRoot, 'dist')
return [
{
enforce: 'pre',
name: 'vitest:browser',
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],
},
}
},
async resolveId(id) {
if (!builtinModules.includes(id) && !polyfills.includes(id) && !id.startsWith('node:'))
return
id = normalizeId(id)
return { id: await polyfillPath(id), moduleSideEffects: false }
},
},
]
}
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
}