From 5cba637c4ec39c06794146b0c7fd3225d26dcabb Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 9 Jan 2024 16:29:43 +0800 Subject: [PATCH] Improve env var handling in SSR (#9637) --- .changeset/curvy-socks-rhyme.md | 5 +++++ packages/astro/src/core/create-vite.ts | 10 +++++++--- packages/astro/src/vite-plugin-env/index.ts | 18 ------------------ 3 files changed, 12 insertions(+), 21 deletions(-) create mode 100644 .changeset/curvy-socks-rhyme.md diff --git a/.changeset/curvy-socks-rhyme.md b/.changeset/curvy-socks-rhyme.md new file mode 100644 index 0000000000..485402efee --- /dev/null +++ b/.changeset/curvy-socks-rhyme.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Improves environment variables replacement in SSR diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index a3edff3b91..4ce605b9f5 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -149,9 +149,9 @@ export async function createVite( root: fileURLToPath(settings.config.root), envPrefix: settings.config.vite?.envPrefix ?? 'PUBLIC_', define: { - 'import.meta.env.SITE': settings.config.site - ? JSON.stringify(settings.config.site) - : 'undefined', + 'import.meta.env.SITE': stringifyForDefine(settings.config.site), + 'import.meta.env.BASE_URL': stringifyForDefine(settings.config.base), + 'import.meta.env.ASSETS_PREFIX': stringifyForDefine(settings.config.build.assetsPrefix), }, server: { hmr: @@ -308,3 +308,7 @@ function isCommonNotAstro(dep: string): boolean { ) ); } + +function stringifyForDefine(value: string | undefined): string { + return typeof value === 'string' ? JSON.stringify(value) : 'undefined'; +} diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index 1958344e59..c52a345be4 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -48,12 +48,6 @@ function getPrivateEnv( } } } - privateEnv.SITE = astroConfig.site ? JSON.stringify(astroConfig.site) : 'undefined'; - privateEnv.SSR = JSON.stringify(true); - privateEnv.BASE_URL = astroConfig.base ? JSON.stringify(astroConfig.base) : 'undefined'; - privateEnv.ASSETS_PREFIX = astroConfig.build.assetsPrefix - ? JSON.stringify(astroConfig.build.assetsPrefix) - : 'undefined'; return privateEnv; } @@ -74,18 +68,6 @@ export default function envVitePlugin({ settings }: EnvPluginOptions): vite.Plug return { name: 'astro:vite-plugin-env', enforce: 'pre', - config() { - return { - define: { - 'import.meta.env.BASE_URL': astroConfig.base - ? JSON.stringify(astroConfig.base) - : 'undefined', - 'import.meta.env.ASSETS_PREFIX': astroConfig.build.assetsPrefix - ? JSON.stringify(astroConfig.build.assetsPrefix) - : 'undefined', - }, - }; - }, configResolved(resolvedConfig) { viteConfig = resolvedConfig; },