Skip to content

Commit 08d093c

Browse files
XiSenaosapphi-red
andauthored
fix(worker): replace import.meta correctly for IIFE worker (#15321)
Co-authored-by: 翠 / green <green@sapphi.red>
1 parent 0506812 commit 08d093c

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

packages/vite/src/node/plugins/worker.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,21 @@ export async function workerFileToUrl(
165165
export function webWorkerPostPlugin(): Plugin {
166166
return {
167167
name: 'vite:worker-post',
168-
resolveImportMeta(property, { chunkId, format }) {
168+
resolveImportMeta(property, { format }) {
169169
// document is undefined in the worker, so we need to avoid it in iife
170-
if (property === 'url' && format === 'iife') {
171-
return 'self.location.href'
170+
if (format === 'iife') {
171+
// compiling import.meta
172+
if (!property) {
173+
// rollup only supports `url` property. we only support `url` property as well.
174+
// https://github.com/rollup/rollup/blob/62b648e1cc6a1f00260bb85aa2050097bb4afd2b/src/ast/nodes/MetaProperty.ts#L164-L173
175+
return `{
176+
url: self.location.href
177+
}`
178+
}
179+
// compiling import.meta.url
180+
if (property === 'url') {
181+
return 'self.location.href'
182+
}
172183
}
173184

174185
return null

playground/worker/__tests__/iife/iife-worker.spec.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -114,17 +114,17 @@ describe.runIf(isBuild)('build', () => {
114114
test('module worker', async () => {
115115
await untilUpdated(
116116
async () => page.textContent('.worker-import-meta-url'),
117-
/A\sstring.*\/iife\/.+url-worker\.js/,
117+
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
118118
true,
119119
)
120120
await untilUpdated(
121121
() => page.textContent('.worker-import-meta-url-resolve'),
122-
/A\sstring.*\/iife\/.+url-worker\.js/,
122+
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
123123
true,
124124
)
125125
await untilUpdated(
126126
() => page.textContent('.worker-import-meta-url-without-extension'),
127-
'A string',
127+
/A\sstring.*\/iife\/.+url-worker\.js.+url-worker\.js/,
128128
true,
129129
)
130130
await untilUpdated(

playground/worker/url-worker.js

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ self.postMessage(
33
'A string',
44
import.meta.env.BASE_URL,
55
self.location.url,
6+
import.meta && import.meta.url,
67
import.meta.url,
78
].join(' '),
89
)

0 commit comments

Comments
 (0)