@@ -31,16 +31,24 @@ export function definePlugin(config: ResolvedConfig): Plugin {
3131 } )
3232 }
3333
34- const env = { ...config . env }
3534 const userDefine : Record < string , string > = { }
35+ const userDefineEnv : Record < string , string > = { }
3636 for ( const key in config . define ) {
3737 const val = config . define [ key ]
3838 userDefine [ key ] = typeof val === 'string' ? val : JSON . stringify ( val )
3939
4040 // 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+ }
4452 }
4553 }
4654
@@ -49,16 +57,21 @@ export function definePlugin(config: ResolvedConfig): Plugin {
4957 const importMetaKeys : Record < string , string > = { }
5058 const importMetaFallbackKeys : Record < string , string > = { }
5159 if ( isBuild ) {
52- env . SSR = ! ! config . build . ssr
53-
60+ const env : Record < string , any > = {
61+ ...config . env ,
62+ SSR : ! ! config . build . ssr ,
63+ }
5464 // set here to allow override with config.define
5565 importMetaKeys [ 'import.meta.hot' ] = `undefined`
5666 for ( const key in env ) {
5767 importMetaKeys [ `import.meta.env.${ key } ` ] = JSON . stringify ( env [ key ] )
5868 }
5969 Object . assign ( importMetaFallbackKeys , {
6070 '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+ ) ,
6275 } )
6376 }
6477
0 commit comments