Skip to content

Commit

Permalink
fix: inject esbuild helpers in IIFE and UMD wrappers (#7948)
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Apr 30, 2022
1 parent 71b1443 commit f7d2d71
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/playground/lib/__tests__/lib.spec.ts
Expand Up @@ -9,10 +9,22 @@ if (isBuild) {

test('umd', async () => {
expect(await page.textContent('.umd')).toBe('It works')
const code = fs.readFileSync(
path.join(testDir, 'dist/my-lib-custom-filename.umd.js'),
'utf-8'
)
// esbuild helpers are injected inside of the UMD wrapper
expect(code).toMatch(/^\(function\(/)
})

test('iife', async () => {
expect(await page.textContent('.iife')).toBe('It works')
const code = fs.readFileSync(
path.join(testDir, 'dist/my-lib-custom-filename.iife.js'),
'utf-8'
)
// esbuild helpers are injected inside of the IIFE wrapper
expect(code).toMatch(/^var MyLib=function\(\){"use strict";/)
})

test('Library mode does not include `preload`', async () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/playground/lib/src/main.js
@@ -1,3 +1,6 @@
export default function myLib(sel) {
// Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
console.log({ ...'foo' })

document.querySelector(sel).textContent = 'It works'
}
25 changes: 25 additions & 0 deletions packages/vite/src/node/plugins/esbuild.ts
Expand Up @@ -26,6 +26,11 @@ import { searchForWorkspaceRoot } from '..'

const debug = createDebugger('vite:esbuild')

const INJECT_HELPERS_IIFE_RE =
/(.*)(var [^\s]+=function\(.*\){"use strict";)(.*)/
const INJECT_HELPERS_UMD_RE =
/(.*)(\(function\(.*\){.+amd.+function\(.*\){"use strict";)(.*)/

let server: ViteDevServer

export interface ESBuildOptions extends TransformOptions {
Expand Down Expand Up @@ -254,6 +259,26 @@ export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => {
}
: undefined)
})

if (config.build.lib) {
// #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
// names are minified potentially causing collision with other globals.
// We use a regex to inject the helpers inside the wrappers.
// We don't need to create a MagicString here because both the helpers and
// the headers don't modify the sourcemap
const injectHelpers =
opts.format === 'umd'
? INJECT_HELPERS_UMD_RE
: opts.format === 'iife'
? INJECT_HELPERS_IIFE_RE
: undefined
if (injectHelpers) {
res.code = res.code.replace(
injectHelpers,
(_, helpers, header, rest) => header + helpers + rest
)
}
}
return res
}
}
Expand Down

0 comments on commit f7d2d71

Please sign in to comment.