Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: inject esbuild helpers in IIFE and UMD wrappers #7948

Merged
merged 2 commits into from Apr 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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