Skip to content

Commit

Permalink
refactor(importAnalysis): cache injected env string (#12154)
Browse files Browse the repository at this point in the history
Co-authored-by: bluwy <bjornlu.dev@gmail.com>
  • Loading branch information
sun0day and bluwy authored Feb 26, 2023
1 parent 8a98aef commit 2aad552
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',

Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 2aad552

Please sign in to comment.