I'm trying to import a module in a web worker that imports another module and getting the following error Uncaught SyntaxError: Cannot use import statement outside a module.
My web worker is importing scripts like this:
importScripts(
'./utils.js',
'./nn.js'
);
The error points to the second line with './utils.js', but its actual origin is the first line of utils.js which is the following:
import * as DG from 'datagrok-api/dg';
I tried setting "type": "module" in package.json, but it results in me being unable to compile my project with Webpack and produces other errors.
I also tried to create a worker with new Worker('my.worker.js', {type: "module"}) so I can use import statements in it, but in this case I'm unable to post a message to the worker and not even getting any error. Also module workers are not supported anywhere except for Chrome.
I tried to manage web workers with workerize-loader, but it doesn't work with Webpack 5 which I'm using.
So my question is: how can I import a module in a web worker that contains module imports?
Using dynamic import inside web worker to import modules works for me:
// js/worker.js
(async () => {
try {
// Load multiple modules concurrently
const [module1, module2, module3] = await Promise.all([
import('./module1.js'),
import('./module2.js'),
import('./module3.js')
]);
// Use the imported modules
module1.hello(); // This will log: Hello from module1!
module2.greet(); // This will log: Greetings from module2!
module3.sayHi(); // This will log: Hi from module3!
} catch (error) {
console.error("Failed to load modules:", error);
}
})();
// main.js
var worker = new Worker('js/worker.js');
You can have a look at a working example: timerWorker.js web worker.
If you're following the example, please note that I had to add timer.js which is utilizing timerWorker.js web worker as module type in html like so:
<script src="js/timer.js" defer type="module"></script>
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With