diff --git a/packages/playground/legacy/__tests__/legacy.spec.ts b/packages/playground/legacy/__tests__/legacy.spec.ts index 0a9a214808c666..787f2168cfc8ec 100644 --- a/packages/playground/legacy/__tests__/legacy.spec.ts +++ b/packages/playground/legacy/__tests__/legacy.spec.ts @@ -12,3 +12,9 @@ test('import.meta.env.LEGACY', async () => { test('transpiles down iterators correctly', async () => { expect(await page.textContent('#iterators')).toMatch('hello') }) + +test('wraps with iife', async () => { + expect(await page.textContent('#babel-helpers')).toMatch( + 'exposed babel helpers: false' + ) +}) diff --git a/packages/playground/legacy/index.html b/packages/playground/legacy/index.html index b2e2c85155799f..0dcb9a6c4b2665 100644 --- a/packages/playground/legacy/index.html +++ b/packages/playground/legacy/index.html @@ -1,4 +1,5 @@
+ diff --git a/packages/playground/legacy/main.js b/packages/playground/legacy/main.js index 18db0a9b7b84c7..c337989413a081 100644 --- a/packages/playground/legacy/main.js +++ b/packages/playground/legacy/main.js @@ -21,3 +21,10 @@ document.getElementById('env').textContent = `is legacy: ${isLegacy}` document.getElementById('iterators').textContent = [...new Set(['hello'])].join( '' ) + +// babel-helpers + +document.getElementById('babel-helpers').textContent = + // Using `String.raw` to inject `@babel/plugin-transform-template-literals` + // helpers. + String.raw`exposed babel helpers: ${window._templateObject != null}` diff --git a/packages/plugin-legacy/index.js b/packages/plugin-legacy/index.js index 3bba50352367ff..63d18954e48eaa 100644 --- a/packages/plugin-legacy/index.js +++ b/packages/plugin-legacy/index.js @@ -276,7 +276,8 @@ function viteLegacyPlugin(options = {}) { () => ({ plugins: [ recordAndRemovePolyfillBabelPlugin(legacyPolyfills), - replaceLegacyEnvBabelPlugin() + replaceLegacyEnvBabelPlugin(), + wrapIIFEBabelPlugin() ] }) ], @@ -600,6 +601,22 @@ function replaceLegacyEnvBabelPlugin() { }) } +function wrapIIFEBabelPlugin() { + return ({ types: t, template }) => { + const buildIIFE = template(';(function(){%%body%%})();') + + return { + name: 'vite-wrap-iife', + post({ path }) { + if (!this.isWrapped) { + this.isWrapped = true + path.replaceWith(t.program(buildIIFE({ body: path.node.body }))) + } + } + } + } +} + module.exports = viteLegacyPlugin viteLegacyPlugin.default = viteLegacyPlugin