Skip to content

Commit 9abdb81

Browse files
fix(plugin-legacy): wrap chunks in IIFE (#3783)
1 parent 9703bcd commit 9abdb81

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

packages/playground/legacy/__tests__/legacy.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,9 @@ test('import.meta.env.LEGACY', async () => {
1212
test('transpiles down iterators correctly', async () => {
1313
expect(await page.textContent('#iterators')).toMatch('hello')
1414
})
15+
16+
test('wraps with iife', async () => {
17+
expect(await page.textContent('#babel-helpers')).toMatch(
18+
'exposed babel helpers: false'
19+
)
20+
})

packages/playground/legacy/index.html

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<h1 id="app"></h1>
22
<div id="env"></div>
33
<div id="iterators"></div>
4+
<div id="babel-helpers"></div>
45
<script type="module" src="./main.js"></script>

packages/playground/legacy/main.js

+7
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,10 @@ document.getElementById('env').textContent = `is legacy: ${isLegacy}`
2121
document.getElementById('iterators').textContent = [...new Set(['hello'])].join(
2222
''
2323
)
24+
25+
// babel-helpers
26+
27+
document.getElementById('babel-helpers').textContent =
28+
// Using `String.raw` to inject `@babel/plugin-transform-template-literals`
29+
// helpers.
30+
String.raw`exposed babel helpers: ${window._templateObject != null}`

packages/plugin-legacy/index.js

+18-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,8 @@ function viteLegacyPlugin(options = {}) {
276276
() => ({
277277
plugins: [
278278
recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
279-
replaceLegacyEnvBabelPlugin()
279+
replaceLegacyEnvBabelPlugin(),
280+
wrapIIFEBabelPlugin()
280281
]
281282
})
282283
],
@@ -600,6 +601,22 @@ function replaceLegacyEnvBabelPlugin() {
600601
})
601602
}
602603

604+
function wrapIIFEBabelPlugin() {
605+
return ({ types: t, template }) => {
606+
const buildIIFE = template(';(function(){%%body%%})();')
607+
608+
return {
609+
name: 'vite-wrap-iife',
610+
post({ path }) {
611+
if (!this.isWrapped) {
612+
this.isWrapped = true
613+
path.replaceWith(t.program(buildIIFE({ body: path.node.body })))
614+
}
615+
}
616+
}
617+
}
618+
}
619+
603620
module.exports = viteLegacyPlugin
604621

605622
viteLegacyPlugin.default = viteLegacyPlugin

0 commit comments

Comments
 (0)