Skip to content

Allow import.meta.env in worker import #20900

@threema-gian

Description

@threema-gian

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:

// 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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions