Skip to content

Commit

Permalink
fix(worker): replace import.meta correctly for IIFE worker (#15321)
Browse files Browse the repository at this point in the history
Co-authored-by: 翠 / green <green@sapphi.red>
  • Loading branch information
XiSenao and sapphi-red authored Dec 12, 2023
1 parent 0506812 commit 08d093c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
17 changes: 14 additions & 3 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,21 @@ export async function workerFileToUrl(
export function webWorkerPostPlugin(): Plugin {
return {
name: 'vite:worker-post',
resolveImportMeta(property, { chunkId, format }) {
resolveImportMeta(property, { format }) {
// document is undefined in the worker, so we need to avoid it in iife
if (property === 'url' && format === 'iife') {
return 'self.location.href'
if (format === 'iife') {
// compiling import.meta
if (!property) {
// rollup only supports `url` property. we only support `url` property as well.
// https://github.com/rollup/rollup/blob/62b648e1cc6a1f00260bb85aa2050097bb4afd2b/src/ast/nodes/MetaProperty.ts#L164-L173
return `{
url: self.location.href
}`
}
// compiling import.meta.url
if (property === 'url') {
return 'self.location.href'
}
}

return null
Expand Down
6 changes: 3 additions & 3 deletions playground/worker/__tests__/iife/iife-worker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,17 @@ describe.runIf(isBuild)('build', () => {
test('module worker', async () => {
await untilUpdated(
async () => page.textContent('.worker-import-meta-url'),
/A\sstring.*\/iife\/.+url-worker\.js/,
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
true,
)
await untilUpdated(
() => page.textContent('.worker-import-meta-url-resolve'),
/A\sstring.*\/iife\/.+url-worker\.js/,
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
true,
)
await untilUpdated(
() => page.textContent('.worker-import-meta-url-without-extension'),
'A string',
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
true,
)
await untilUpdated(
Expand Down
1 change: 1 addition & 0 deletions playground/worker/url-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ self.postMessage(
'A string',
import.meta.env.BASE_URL,
self.location.url,
import.meta && import.meta.url,
import.meta.url,
].join(' '),
)
Expand Down

0 comments on commit 08d093c

Please sign in to comment.