Skip to content

Commit 2aad552

Browse files
sun0daybluwy
andauthored
refactor(importAnalysis): cache injected env string (#12154)
Co-authored-by: bluwy <[email protected]>
1 parent 8a98aef commit 2aad552

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

packages/vite/src/node/plugins/importAnalysis.ts

+21-14
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,26 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
166166
const enablePartialAccept = config.experimental?.hmrPartialAccept
167167
let server: ViteDevServer
168168

169+
let _env: string | undefined
170+
function getEnv(ssr: boolean) {
171+
if (!_env) {
172+
_env = `import.meta.env = ${JSON.stringify({
173+
...config.env,
174+
SSR: '__vite__ssr__vite__',
175+
})};`
176+
// account for user env defines
177+
for (const key in config.define) {
178+
if (key.startsWith(`import.meta.env.`)) {
179+
const val = config.define[key]
180+
_env += `${key} = ${
181+
typeof val === 'string' ? val : JSON.stringify(val)
182+
};`
183+
}
184+
}
185+
}
186+
return _env.replace('"__vite__ssr__vite__"', ssr + '')
187+
}
188+
169189
return {
170190
name: 'vite:import-analysis',
171191

@@ -638,20 +658,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
638658

639659
if (hasEnv) {
640660
// inject import.meta.env
641-
let env = `import.meta.env = ${JSON.stringify({
642-
...config.env,
643-
SSR: !!ssr,
644-
})};`
645-
// account for user env defines
646-
for (const key in config.define) {
647-
if (key.startsWith(`import.meta.env.`)) {
648-
const val = config.define[key]
649-
env += `${key} = ${
650-
typeof val === 'string' ? val : JSON.stringify(val)
651-
};`
652-
}
653-
}
654-
str().prepend(env)
661+
str().prepend(getEnv(ssr))
655662
}
656663

657664
if (hasHMR && !ssr) {

0 commit comments

Comments
 (0)