@@ -46,7 +46,7 @@ export function definePlugin(config: ResolvedConfig): Plugin {
46
46
// stringified for `import.meta.env`, we can remove the quotes and
47
47
// retain being an identifier
48
48
typeof val === 'string' && / ^ [ \p{ L} _ $ ] / u. test ( val . trim ( ) )
49
- ? `__vite__ ${ val } __vite__ `
49
+ ? `__vite__define__ ${ val } `
50
50
: val
51
51
}
52
52
}
@@ -56,34 +56,50 @@ export function definePlugin(config: ResolvedConfig): Plugin {
56
56
const importMetaKeys : Record < string , string > = { }
57
57
const importMetaFallbackKeys : Record < string , string > = { }
58
58
if ( isBuild ) {
59
- const env : Record < string , any > = {
60
- ...config . env ,
61
- SSR : ! ! config . build . ssr ,
62
- }
63
59
// set here to allow override with config.define
64
60
importMetaKeys [ 'import.meta.hot' ] = `undefined`
65
- for ( const key in env ) {
66
- importMetaKeys [ `import.meta.env.${ key } ` ] = JSON . stringify ( env [ key ] )
61
+ for ( const key in config . env ) {
62
+ importMetaKeys [ `import.meta.env.${ key } ` ] = JSON . stringify ( config . env [ key ] )
67
63
}
68
64
Object . assign ( importMetaFallbackKeys , {
69
65
'import.meta.env.' : `({}).` ,
70
- 'import.meta.env' : JSON . stringify ( { ...env , ...userDefineEnv } ) . replace (
71
- / " _ _ v i t e _ _ ( .+ ?) _ _ v i t e _ _ " / g,
72
- ( _ , val ) => val ,
73
- ) ,
66
+ 'import.meta.env' : JSON . stringify ( {
67
+ ...config . env ,
68
+ SSR : '__vite__ssr__' ,
69
+ ...userDefineEnv ,
70
+ } ) . replace ( / " _ _ v i t e _ _ d e f i n e _ _ ( .+ ?) " / g, ( _ , val ) => val ) ,
74
71
} )
75
72
}
76
73
74
+ function getImportMetaKeys ( ssr : boolean ) : Record < string , string > {
75
+ if ( ! isBuild ) return { }
76
+ return {
77
+ ...importMetaKeys ,
78
+ 'import.meta.env.SSR' : ssr + '' ,
79
+ }
80
+ }
81
+
82
+ function getImportMetaFallbackKeys ( ssr : boolean ) : Record < string , string > {
83
+ if ( ! isBuild ) return { }
84
+ return {
85
+ ...importMetaFallbackKeys ,
86
+ 'import.meta.env' : importMetaFallbackKeys [ 'import.meta.env' ] . replace (
87
+ '"__vite__ssr__"' ,
88
+ ssr + '' ,
89
+ ) ,
90
+ }
91
+ }
92
+
77
93
function generatePattern (
78
94
ssr : boolean ,
79
95
) : [ Record < string , string | undefined > , RegExp | null ] {
80
96
const replaceProcessEnv = ! ssr || config . ssr ?. target === 'webworker'
81
97
82
98
const replacements : Record < string , string > = {
83
99
...( replaceProcessEnv ? processNodeEnv : { } ) ,
84
- ...importMetaKeys ,
100
+ ...getImportMetaKeys ( ssr ) ,
85
101
...userDefine ,
86
- ...importMetaFallbackKeys ,
102
+ ...getImportMetaFallbackKeys ( ssr ) ,
87
103
...( replaceProcessEnv ? processEnv : { } ) ,
88
104
}
89
105
0 commit comments