@@ -31,16 +31,24 @@ export function definePlugin(config: ResolvedConfig): Plugin {
31
31
} )
32
32
}
33
33
34
- const env = { ...config . env }
35
34
const userDefine : Record < string , string > = { }
35
+ const userDefineEnv : Record < string , string > = { }
36
36
for ( const key in config . define ) {
37
37
const val = config . define [ key ]
38
38
userDefine [ key ] = typeof val === 'string' ? val : JSON . stringify ( val )
39
39
40
40
// make sure `import.meta.env` object has user define properties
41
- const match = key . match ( metaEnvRe )
42
- if ( match ) {
43
- env [ match [ 1 ] ] = val
41
+ if ( isBuild ) {
42
+ const match = key . match ( metaEnvRe )
43
+ if ( match ) {
44
+ userDefineEnv [ match [ 1 ] ] =
45
+ // test if value is raw identifier to wrap with __vite__ so when
46
+ // stringified for `import.meta.env`, we can remove the quotes and
47
+ // retain being an identifier
48
+ typeof val === 'string' && / ^ [ \p{ L} _ $ ] / u. test ( val . trim ( ) )
49
+ ? `__vite__${ val } __vite__`
50
+ : val
51
+ }
44
52
}
45
53
}
46
54
@@ -49,16 +57,21 @@ export function definePlugin(config: ResolvedConfig): Plugin {
49
57
const importMetaKeys : Record < string , string > = { }
50
58
const importMetaFallbackKeys : Record < string , string > = { }
51
59
if ( isBuild ) {
52
- env . SSR = ! ! config . build . ssr
53
-
60
+ const env : Record < string , any > = {
61
+ ...config . env ,
62
+ SSR : ! ! config . build . ssr ,
63
+ }
54
64
// set here to allow override with config.define
55
65
importMetaKeys [ 'import.meta.hot' ] = `undefined`
56
66
for ( const key in env ) {
57
67
importMetaKeys [ `import.meta.env.${ key } ` ] = JSON . stringify ( env [ key ] )
58
68
}
59
69
Object . assign ( importMetaFallbackKeys , {
60
70
'import.meta.env.' : `({}).` ,
61
- 'import.meta.env' : JSON . stringify ( env ) ,
71
+ 'import.meta.env' : JSON . stringify ( { ...env , ...userDefineEnv } ) . replace (
72
+ / " _ _ v i t e _ _ ( .+ ?) _ _ v i t e _ _ " / g,
73
+ ( _ , val ) => val ,
74
+ ) ,
62
75
} )
63
76
}
64
77
0 commit comments