From 2aad5522dcd30050ef049170825287dfa0d0aa42 Mon Sep 17 00:00:00 2001 From: sun0day Date: Sun, 26 Feb 2023 11:10:44 +0800 Subject: [PATCH] refactor(importAnalysis): cache injected env string (#12154) Co-authored-by: bluwy --- .../vite/src/node/plugins/importAnalysis.ts | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index 75d0b57f0188f6..b49a920044984a 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -166,6 +166,26 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { const enablePartialAccept = config.experimental?.hmrPartialAccept let server: ViteDevServer + let _env: string | undefined + function getEnv(ssr: boolean) { + if (!_env) { + _env = `import.meta.env = ${JSON.stringify({ + ...config.env, + SSR: '__vite__ssr__vite__', + })};` + // account for user env defines + for (const key in config.define) { + if (key.startsWith(`import.meta.env.`)) { + const val = config.define[key] + _env += `${key} = ${ + typeof val === 'string' ? val : JSON.stringify(val) + };` + } + } + } + return _env.replace('"__vite__ssr__vite__"', ssr + '') + } + return { name: 'vite:import-analysis', @@ -638,20 +658,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { if (hasEnv) { // inject import.meta.env - let env = `import.meta.env = ${JSON.stringify({ - ...config.env, - SSR: !!ssr, - })};` - // account for user env defines - for (const key in config.define) { - if (key.startsWith(`import.meta.env.`)) { - const val = config.define[key] - env += `${key} = ${ - typeof val === 'string' ? val : JSON.stringify(val) - };` - } - } - str().prepend(env) + str().prepend(getEnv(ssr)) } if (hasHMR && !ssr) {