diff --git a/packages/vite/src/node/plugins/define.ts b/packages/vite/src/node/plugins/define.ts index 11135dcb03b0d6..dc373b6c30b682 100644 --- a/packages/vite/src/node/plugins/define.ts +++ b/packages/vite/src/node/plugins/define.ts @@ -31,16 +31,24 @@ export function definePlugin(config: ResolvedConfig): Plugin { }) } - const env = { ...config.env } const userDefine: Record = {} + const userDefineEnv: Record = {} for (const key in config.define) { const val = config.define[key] userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val) // make sure `import.meta.env` object has user define properties - const match = key.match(metaEnvRe) - if (match) { - env[match[1]] = val + if (isBuild) { + const match = key.match(metaEnvRe) + if (match) { + userDefineEnv[match[1]] = + // test if value is raw identifier to wrap with __vite__ so when + // stringified for `import.meta.env`, we can remove the quotes and + // retain being an identifier + typeof val === 'string' && /^[\p{L}_$]/u.test(val.trim()) + ? `__vite__${val}__vite__` + : val + } } } @@ -49,8 +57,10 @@ export function definePlugin(config: ResolvedConfig): Plugin { const importMetaKeys: Record = {} const importMetaFallbackKeys: Record = {} if (isBuild) { - env.SSR = !!config.build.ssr - + const env: Record = { + ...config.env, + SSR: !!config.build.ssr, + } // set here to allow override with config.define importMetaKeys['import.meta.hot'] = `undefined` for (const key in env) { @@ -58,7 +68,10 @@ export function definePlugin(config: ResolvedConfig): Plugin { } Object.assign(importMetaFallbackKeys, { 'import.meta.env.': `({}).`, - 'import.meta.env': JSON.stringify(env), + 'import.meta.env': JSON.stringify({ ...env, ...userDefineEnv }).replace( + /"__vite__(.+?)__vite__"/g, + (_, val) => val, + ), }) } diff --git a/playground/legacy/__tests__/legacy.spec.ts b/playground/legacy/__tests__/legacy.spec.ts index 320cd5b72d7e91..eb71185f3c8446 100644 --- a/playground/legacy/__tests__/legacy.spec.ts +++ b/playground/legacy/__tests__/legacy.spec.ts @@ -23,6 +23,7 @@ test('import.meta.env.LEGACY', async () => { isBuild ? 'true' : 'false', true, ) + await untilUpdated(() => page.textContent('#env-equal'), 'true', true) }) // https://github.com/vitejs/vite/issues/3400 diff --git a/playground/legacy/index.html b/playground/legacy/index.html index 636029da7384eb..d5a73323a20e77 100644 --- a/playground/legacy/index.html +++ b/playground/legacy/index.html @@ -1,5 +1,6 @@

+
diff --git a/playground/legacy/main.js b/playground/legacy/main.js index ed04ee8ab63cd0..7a42c3cf23a138 100644 --- a/playground/legacy/main.js +++ b/playground/legacy/main.js @@ -20,6 +20,9 @@ if (import.meta.env.LEGACY) { text('#env', `is legacy: ${isLegacy}`) +const metaEnvObj = import.meta.env +text('#env-equal', import.meta.env.LEGACY === metaEnvObj.LEGACY) + // Iterators text('#iterators', [...new Set(['hello'])].join(''))