diff --git a/docs/guide/features.md b/docs/guide/features.md
index dfd8c57f715ded..59d3883fe19b85 100644
--- a/docs/guide/features.md
+++ b/docs/guide/features.md
@@ -657,7 +657,15 @@ const worker = new Worker(new URL('./worker.js', import.meta.url), {
})
```
-The worker detection will only work if the `new URL()` constructor is used directly inside the `new Worker()` declaration. Additionally, all options parameters must be static values (i.e. string literals).
+The worker detection will only work if the `new URL()` constructor is used directly inside the `new Worker()` declaration. Additionally, all options parameters must be static values (i.e. string literals), or a variable that is defined before the `new Worker()`, as follows:
+
+```ts
+const workerOptions = { type: 'module' }
+const worker = new Worker(
+ new URL('./worker.js', import.meta.url),
+ workerOptions,
+)
+```
### Import with Query Suffixes
diff --git a/packages/vite/src/node/plugins/workerImportMetaUrl.ts b/packages/vite/src/node/plugins/workerImportMetaUrl.ts
index 8d8d316a4ec214..016f61696b08f7 100644
--- a/packages/vite/src/node/plugins/workerImportMetaUrl.ts
+++ b/packages/vite/src/node/plugins/workerImportMetaUrl.ts
@@ -34,7 +34,7 @@ function parseWorkerOptions(
opts = evalValueformat iife:
++ var workerOptions = { type: 'module' } new Worker(new URL('./url-worker.js', + import.meta.url), workerOptions) + .worker-import-meta-url-via-variable +
+
+
new SharedWorker(new URL('./url-shared-worker.js', import.meta.url), { type: 'module' }) diff --git a/playground/worker/worker/main-module.js b/playground/worker/worker/main-module.js index a59bc903800b12..590b915a83ecee 100644 --- a/playground/worker/worker/main-module.js +++ b/playground/worker/worker/main-module.js @@ -135,6 +135,17 @@ wWithoutExt.addEventListener('message', (ev) => text('.worker-import-meta-url-without-extension', JSON.stringify(ev.data)), ) +const myWorkerOptions = { type: 'module' } + +// url import worker via variable +const wViaVariable = new Worker( + new URL('../url-worker', import.meta.url), + myWorkerOptions, +) +wViaVariable.addEventListener('message', (ev) => + text('.worker-import-meta-url-via-variable', JSON.stringify(ev.data)), +) + const genWorkerName = () => 'module' const w2 = new SharedWorker( new URL('../url-shared-worker.js', import.meta.url),