-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
define.ts
149 lines (129 loc) · 4.45 KB
/
define.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
import MagicString from 'magic-string'
import type { TransformResult } from 'rollup'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { isCSSRequest } from './css'
import { isHTMLRequest } from './html'
const nonJsRe = /\.(json)($|\?)/
const isNonJsRequest = (request: string): boolean => nonJsRe.test(request)
export function definePlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
const isBuildLib = isBuild && config.build.lib
// ignore replace process.env in lib build
const processEnv: Record<string, string> = {}
const processNodeEnv: Record<string, string> = {}
if (!isBuildLib) {
const nodeEnv = process.env.NODE_ENV || config.mode
Object.assign(processEnv, {
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
})
Object.assign(processNodeEnv, {
'process.env.NODE_ENV': JSON.stringify(nodeEnv),
'global.process.env.NODE_ENV': JSON.stringify(nodeEnv),
'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv)
})
}
const userDefine: Record<string, string> = {}
for (const key in config.define) {
const val = config.define[key]
userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val)
}
// during dev, import.meta properties are handled by importAnalysis plugin.
// ignore replace import.meta.env in lib build
const importMetaKeys: Record<string, string> = {}
if (isBuild) {
const env: Record<string, any> = {
...config.env,
SSR: !!config.build.ssr
}
for (const key in env) {
importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(env[key])
}
Object.assign(importMetaKeys, {
'import.meta.env.': `({}).`,
'import.meta.env': JSON.stringify(config.env),
'import.meta.hot': `false`
})
}
function generatePattern(
ssr: boolean
): [Record<string, string | undefined>, RegExp | null] {
const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker'
const replacements: Record<string, string> = {
...(replaceProcessEnv ? processNodeEnv : {}),
...userDefine,
...importMetaKeys,
...(replaceProcessEnv ? processEnv : {})
}
const replacementsKeys = Object.keys(replacements)
const pattern = replacementsKeys.length
? new RegExp(
// Mustn't be preceded by a char that can be part of an identifier
// or a '.' that isn't part of a spread operator
'(?<![\\p{L}\\p{N}_$]|(?<!\\.\\.)\\.)(' +
replacementsKeys
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
// Mustn't be followed by a char that can be part of an identifier
// or an assignment (but allow equality operators)
')(?![\\p{L}\\p{N}_$]|\\s*?=[^=])',
'gu'
)
: null
return [replacements, pattern]
}
const defaultPattern = generatePattern(false)
const ssrPattern = generatePattern(true)
return {
name: 'vite:define',
transform(code, id, options) {
const ssr = options?.ssr === true
if (!ssr && !isBuild) {
// for dev we inject actual global defines in the vite client to
// avoid the transform cost.
return
}
if (
// exclude html, css and static assets for performance
isHTMLRequest(id) ||
isCSSRequest(id) ||
isNonJsRequest(id) ||
config.assetsInclude(id)
) {
return
}
const [replacements, pattern] = ssr ? ssrPattern : defaultPattern
if (!pattern) {
return null
}
if (ssr && !isBuild) {
// ssr + dev, simple replace
return code.replace(pattern, (_, match) => {
return '' + replacements[match]
})
}
const s = new MagicString(code)
let hasReplaced = false
let match: RegExpExecArray | null
while ((match = pattern.exec(code))) {
hasReplaced = true
const start = match.index
const end = start + match[0].length
const replacement = '' + replacements[match[1]]
s.overwrite(start, end, replacement, { contentOnly: true })
}
if (!hasReplaced) {
return null
}
const result: TransformResult = { code: s.toString() }
if (config.build.sourcemap) {
result.map = s.generateMap({ hires: true })
}
return result
}
}
}