forked from vitest-dev/vitest
/
envReplacer.ts
35 lines (29 loc) · 931 Bytes
/
envReplacer.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
import MagicString from 'magic-string'
import type { Plugin } from 'vite'
import { stripLiteral } from 'strip-literal'
// so people can reassign envs at runtime
// import.meta.env.VITE_NAME = 'app' -> process.env.VITE_NAME = 'app'
export const EnvReplacerPlugin = (): Plugin => {
return {
name: 'vitest:env-replacer',
enforce: 'pre',
transform(code, id) {
if (!/\bimport\.meta\.env\b/g.test(code))
return null
let s: MagicString | null = null
const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g)
for (const env of envs) {
s ||= new MagicString(code)
const startIndex = env.index!
const endIndex = startIndex + env[0].length
s.overwrite(startIndex, endIndex, 'process.env')
}
if (s) {
return {
code: s.toString(),
map: s.generateMap({ hires: true, source: id }),
}
}
},
}
}