Skip to content

Commit

Permalink
fix(plugin-legacy): wrap chunks in IIFE (#3783)
Browse files Browse the repository at this point in the history
  • Loading branch information
avocadowastaken authored Jun 13, 2021
1 parent 9703bcd commit 9abdb81
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/playground/legacy/__tests__/legacy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
)
})
1 change: 1 addition & 0 deletions packages/playground/legacy/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<h1 id="app"></h1>
<div id="env"></div>
<div id="iterators"></div>
<div id="babel-helpers"></div>
<script type="module" src="./main.js"></script>
7 changes: 7 additions & 0 deletions packages/playground/legacy/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`
19 changes: 18 additions & 1 deletion packages/plugin-legacy/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,8 @@ function viteLegacyPlugin(options = {}) {
() => ({
plugins: [
recordAndRemovePolyfillBabelPlugin(legacyPolyfills),
replaceLegacyEnvBabelPlugin()
replaceLegacyEnvBabelPlugin(),
wrapIIFEBabelPlugin()
]
})
],
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 9abdb81

Please sign in to comment.