Reputation: 9819
How can a script use Javascript imports
/ require
in a Web Workers script and bundle it up to using Webpack without using Worker-Loader
or any other "plugin" abstraction — only using the browsers Web Worker API?
Via Webpack, I'm able to produce two scripts: main.js
and worker.js
. Webpack file is setup to transpile both files.
In main.js
instantiate a new worker const worker = new Worker('worker.js')
.
Worker script is simple:
/// worker.js
onmessage = function foo() {
postMessage('test');
};
In main.js
, postMessage()
works as expected.
But once any module is imported into the worker, things break.
/// worker.js
import bar from 'bar';
onmessage = function foo() {
postMessage('test');
};
Upvotes: 1
Views: 1375
Reputation: 136618
There is a type: "module"
option you can pass to your Worker's constructor:
const worker = new Worker( url, { type: 'module' } );
Upvotes: 1