Allow importing classic Web Workers (not Module Workers)
See original GitHub issueVite provides an easy way to import Web Workers, as described in the docs:
import MyWorker from './worker?worker'
const worker = new MyWorker()
This gets compiled into module worker initialization:
new Worker("/assets/index.ef0da162.js",{type:"module"})
Module workers are different from classic workers, and their support is very limited (Chrome 80+, no Safari, no Firefox), which means that shipping this code is not an option.
What’s more, module workers are not drop-in replacement for classic workers, as they don’t support importScripts
, which existing implementations rely on to import scripts from CDN:
importScripts('https://unpkg.com/comlink/dist/umd/comlink.js')
importScripts('https://www.gstatic.com/firebasejs/8.3.0/firebase-app.js')
I would like to request support for classic workers by allowing to pass worker options to the worker constructor:
import MyWorker from './worker?worker'
const worker = new MyWorker() // classic worker
const worker = new MyWorker({type: 'classic'}) // classic worker
const worker = new MyWorker({type: 'module'}) // module worker
Worker constructor options should allow all of worker options, which look like this:
interface WorkerOptions {
credentials?: RequestCredentials;
name?: string;
type?: WorkerType;
}
–
The alternative right now is to bundle worker code in a separate process and use the usual worker initialization:
const classicWorker = new Worker('./worker-built-separately.js')
This complicates the process and doesn’t provide out of the box file name hashing. To add file name hashing would require further complications.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:27
- Comments:11 (4 by maintainers)
Top GitHub Comments
Is there a way to build with vite the worker with all its dependencies inside (no code splitting)?
I’m testing web workers and I can use
{ type: 'module'}
(viaesno
+tsup
withesm
orcjs
formats) on Safari and Firefox, the only restriction is to not have imports inside the worker (just plan javascript, es2017 or whatever we want) and building the worker with all dependencies inside requires to configure its dependencies asdev dependencies
(in my caseComlink
anddexiejs
).For example, I get my logic and put on new project, then I configure
scripts
directory with:scripts/build.ts
where
commands.ts
is:then I add a new
script
to mypackage.json
:My worker looks like this
parse-file-worker-module.ts
:and finally I can use it (just setting the output on public directory) and referencing it via:
yes, I add the options to show the
classic
word. hhh