From bace7244e776b3f4c9dd7e3ff1885df668cbcb87 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sat, 13 Feb 2021 14:47:35 -0500 Subject: [PATCH] fix(plugin-legacy): prevent constant folding for import.meta.env.LEGACY close #1999 --- packages/playground/legacy/main.js | 13 ++++++++++--- packages/plugin-legacy/index.js | 6 +++--- packages/plugin-legacy/package.json | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/packages/playground/legacy/main.js b/packages/playground/legacy/main.js index 84409b57793631..631f589eb541d8 100644 --- a/packages/playground/legacy/main.js +++ b/packages/playground/legacy/main.js @@ -5,6 +5,13 @@ async function run() { run() -document.getElementById('env').textContent = `is legacy: ${ - import.meta.env.LEGACY -}` +let isLegacy + +// make sure that branching works despite esbuild's constant folding (#1999) +if (import.meta.env.LEGACY) { + if (import.meta.env.LEGACY === true) isLegacy = true +} else { + if (import.meta.env.LEGACY === false) isLegacy = false +} + +document.getElementById('env').textContent = `is legacy: ${isLegacy}` diff --git a/packages/plugin-legacy/index.js b/packages/plugin-legacy/index.js index 32f0a48f58ddcf..9d1cfd4acaf72b 100644 --- a/packages/plugin-legacy/index.js +++ b/packages/plugin-legacy/index.js @@ -189,7 +189,7 @@ function viteLegacyPlugin(options = {}) { } if (raw.includes(legacyEnvVarMarker)) { - const re = new RegExp(`"${legacyEnvVarMarker}"`, 'g') + const re = new RegExp(legacyEnvVarMarker, 'g') if (config.build.sourcemap) { const s = new MagicString(raw) let match @@ -550,8 +550,8 @@ function replaceLegacyEnvBabelPlugin() { return ({ types: t }) => ({ name: 'vite-replace-env-legacy', visitor: { - StringLiteral(path) { - if (path.node.value === legacyEnvVarMarker) { + Identifier(path) { + if (path.node.name === legacyEnvVarMarker) { path.replaceWith(t.booleanLiteral(true)) } } diff --git a/packages/plugin-legacy/package.json b/packages/plugin-legacy/package.json index 0dc6d0cc0aea1d..b7cb6cadb599e5 100644 --- a/packages/plugin-legacy/package.json +++ b/packages/plugin-legacy/package.json @@ -32,6 +32,6 @@ "systemjs": "^6.8.3" }, "peerDependencies": { - "vite": "^2.0.0-beta.12" + "vite": "^2.0.0-beta.70" } }