From 3e0cd3d98e612de4bd21125d151dbb14f35a64f0 Mon Sep 17 00:00:00 2001 From: julienv3 Date: Mon, 28 Nov 2022 16:03:34 -0500 Subject: [PATCH] fix: import.meta.env and process.env undefined variable replacement (fix #8663) (#10958) Co-authored-by: bluwy fix https://github.com/vitejs/vite/issues/8663 --- packages/vite/src/node/plugins/define.ts | 2 +- playground/define/__tests__/define.spec.ts | 8 +++++++- playground/define/commonjs-dep/index.js | 6 +++++- playground/define/index.html | 8 +++++++- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/vite/src/node/plugins/define.ts b/packages/vite/src/node/plugins/define.ts index 47394b7f14e635..8743b6d8b4e7c5 100644 --- a/packages/vite/src/node/plugins/define.ts +++ b/packages/vite/src/node/plugins/define.ts @@ -85,7 +85,7 @@ export function definePlugin(config: ResolvedConfig): Plugin { .join('|') + // Mustn't be followed by a char that can be part of an identifier // or an assignment (but allow equality operators) - ')(?![\\p{L}\\p{N}_$]|\\s*?=[^=])', + ')(?:(?<=\\.)|(?![\\p{L}\\p{N}_$]|\\s*?=[^=]))', 'gu' ) : null diff --git a/playground/define/__tests__/define.spec.ts b/playground/define/__tests__/define.spec.ts index 43787ef0adb112..8c27686bce1703 100644 --- a/playground/define/__tests__/define.spec.ts +++ b/playground/define/__tests__/define.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from 'vitest' import viteConfig from '../vite.config' -import { page } from '~utils' +import { isBuild, page } from '~utils' test('string', async () => { const defines = viteConfig.define @@ -44,4 +44,10 @@ test('string', async () => { expect(await page.textContent('.define-in-dep')).toBe( defines.__STRINGIFIED_OBJ__ ) + expect(await page.textContent('.import-meta-env-undefined')).toBe( + isBuild ? '({}).UNDEFINED' : 'import.meta.env.UNDEFINED' + ) + expect(await page.textContent('.process-env-undefined')).toBe( + isBuild ? '({}).UNDEFINED' : 'process.env.UNDEFINED' + ) }) diff --git a/playground/define/commonjs-dep/index.js b/playground/define/commonjs-dep/index.js index 23e0bf1b32e32f..9be5641e04b844 100644 --- a/playground/define/commonjs-dep/index.js +++ b/playground/define/commonjs-dep/index.js @@ -1 +1,5 @@ -module.exports = { defined: __STRINGIFIED_OBJ__ } +module.exports = { + defined: __STRINGIFIED_OBJ__, + importMetaEnvUndefined: 'import.meta.env.UNDEFINED', + processEnvUndefined: 'process.env.UNDEFINED' +} diff --git a/playground/define/index.html b/playground/define/index.html index c4f4c598aba563..06b2f4f9479d38 100644 --- a/playground/define/index.html +++ b/playground/define/index.html @@ -17,6 +17,10 @@

Define

define variable in html: __EXP__

import json:

define in dep:

+

+ import.meta.env.UNDEFINED: +

+

process.env.UNDEFINED: