Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/playground/lib/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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