-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Description
Description
The following is currently not possible in Vite (7.1.5):
const worker = new Worker(
new URL(
`../some/path/${import.meta.env.MY_VAR}/backend-worker.ts`,
import.meta.url,
),
{
type: 'module',
},
);That's because template strings are currently disallowed if they contain an expression, due to the following check:
vite/packages/vite/src/node/plugins/workerImportMetaUrl.ts
Lines 228 to 234 in 73b6d24
| // potential dynamic template string | |
| if (rawUrl[0] === '`' && rawUrl.includes('${')) { | |
| this.error( | |
| `\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, | |
| expStart, | |
| ) | |
| } |
This results in the following error message: new URL(url, import.meta.url) is not supported in dynamic template string.
Suggested solution
First, I tried to disable the check entirely (just to see if it would work out of the box), but that results in another error (but Vite itself correctly expands the env variable!): [vite:build-html] Could not resolve entry module "src/some/path/${"some-value"}/backend-worker.ts". Side note: that error seems to originate in Rollup.
My initial idea was to just tighten the check to allow template strings in the worker URL if they only contain import.meta.env and plain string expressions. However, because of that Rollup error, I suspect the solution will not be quite as simple.
Alternative
As a workaround, the following seems to work fine:
const worker = new Worker(
new URL(
'../some/path/' + import.meta.env.MY_VAR + '/backend-worker.ts',
import.meta.url,
),
{
type: 'module',
},
);Additional context
This error was the reason we were using a custom plugin for the worker imports, which @sapphi-red asked us about in #20720. While the workaround should allow us to remove that plugin altogether, it would still be nice if worker URLs would support template strings with import.meta.env in Vite.
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.