feat: make Worker constructors configurable #16422
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR addresses some first parts of #16128
Background
As described in the issue the ultimate goal is to make the Web Worker generation reusable from other plugins. This way a custom plugin for a specific library can tell vite more specifically to generate workers for this specific library.
In preparation to such flexibility, this PR adds the possibility to use alternative constructors than
Worker
andSharedWorker
.Use Cases
I envision as a next step that the functionality behind
workerImportMetaUrlPlugin
is exposed for plugin authors to trigger worker generation specifically for their plugin.Adding audio and paint worklets as new types of "workers" will require a certain degree of flexibility to tell vite which syntax to pick up as worklets. (e.g.
context.audioWorklet.addModule(new URL('./worklet.js', import.meta.url))
could be added asworker: [{ function: 'context.audioWorklet.addModule', kind: 'worklet' }]
Dependency
The
escape-string-regexp
is needed as new dependency to escape the input strings in the constructor regex matching. The dependency seems quite widely adopted but is also very lightweight:https://www.npmjs.com/package/escape-string-regexp
https://github.com/sindresorhus/escape-string-regexp/blob/main/index.js#L8