diff --git a/packages/plugin-legacy/src/index.ts b/packages/plugin-legacy/src/index.ts index e7919ea82a651f..42f7b44ce80158 100644 --- a/packages/plugin-legacy/src/index.ts +++ b/packages/plugin-legacy/src/index.ts @@ -118,6 +118,7 @@ function toAssetPathFromHtml( } const legacyEnvVarMarker = `__VITE_IS_LEGACY__` +const modernEnvVarMarker = `__VITE_IS_MODERN__` const _require = createRequire(import.meta.url) @@ -590,6 +591,7 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { plugins: [ recordAndRemovePolyfillBabelPlugin(polyfillsDiscovered.legacy), replaceLegacyEnvBabelPlugin(), + replaceModernEnvBabelPlugin(), wrapIIFEBabelPlugin(), ], }), @@ -1014,6 +1016,19 @@ function replaceLegacyEnvBabelPlugin(): BabelPlugin { }) } +function replaceModernEnvBabelPlugin(): BabelPlugin { + return ({ types: t }): BabelPlugin => ({ + name: 'vite-replace-env-modern', + visitor: { + Identifier(path) { + if (path.node.name === modernEnvVarMarker) { + path.replaceWith(t.booleanLiteral(false)) + } + }, + }, + }) +} + function wrapIIFEBabelPlugin(): BabelPlugin { return ({ types: t, template }): BabelPlugin => { const buildIIFE = template(';(function(){%%body%%})();') diff --git a/playground/legacy/__tests__/legacy.spec.ts b/playground/legacy/__tests__/legacy.spec.ts index a1adb0eb3a2030..e601e34b67a950 100644 --- a/playground/legacy/__tests__/legacy.spec.ts +++ b/playground/legacy/__tests__/legacy.spec.ts @@ -5,6 +5,7 @@ import { isBuild, listAssets, page, + readFile, readManifest, } from '~utils' @@ -161,4 +162,14 @@ describe.runIf(isBuild)('build', () => { expect(findAssetFile(/chunk-async(?!-legacy)/)).not.toMatch(guard) expect(findAssetFile(/index-legacy/)).not.toMatch(guard) }) + + test('should not include preload helper in legacy chunks', async () => { + expect( + listAssets().filter( + (filename) => + filename.includes('-legacy') && + readFile(`dist/assets/${filename}`).includes('Unable to preload'), + ), + ).toStrictEqual([]) + }) })