Skip to content

Commit c22ffbc

Browse files
committed
fix(worker): import.meta should be replaced
1 parent c26f5c3 commit c22ffbc

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

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

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,10 +245,11 @@ export function webWorkerPostPlugin(): Plugin {
245245
name: 'vite:worker-post',
246246
transform: {
247247
filter: {
248-
code: 'import.meta.url',
248+
code: 'import.meta',
249249
},
250+
order: 'post',
250251
async handler(code, id) {
251-
// document is undefined in the worker, so we need to avoid import.meta.url in iife
252+
// import.meta is unavailable in the IIFE worker, so we need to replace it
252253
if (this.environment.config.worker.format === 'iife') {
253254
await init
254255

@@ -260,6 +261,7 @@ export function webWorkerPostPlugin(): Plugin {
260261
return
261262
}
262263

264+
let injectedImportMeta = false
263265
let s: MagicString | undefined
264266
for (const { s: start, e: end, d: dynamicIndex } of imports) {
265267
// is import.meta
@@ -268,6 +270,15 @@ export function webWorkerPostPlugin(): Plugin {
268270
if (prop === '.url') {
269271
s ||= new MagicString(code)
270272
s.overwrite(start, end + 4, 'self.location.href')
273+
} else {
274+
s ||= new MagicString(code)
275+
if (!injectedImportMeta) {
276+
s.prepend(
277+
'const _vite_importMeta = { url: self.location.href };\n',
278+
)
279+
injectedImportMeta = true
280+
}
281+
s.overwrite(start, end, '_vite_importMeta')
271282
}
272283
}
273284
}

0 commit comments

Comments
 (0)