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(worker): replace import.meta correctly for IIFE worker #15321

Merged
merged 4 commits into from
Dec 12, 2023
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
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
}`
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
}
// 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