5

After migrating an application from Webpack 4 and worker-loader to Webpack 5, I'm now using Webpacks built-in solution for importing Web Worker as worker-loader is no longer supported in Webpack 5.

The solution provided by Webpack works, except when I use local module imports inside my Workers. Just to be clear:

Following the Webpack documentation I import the Worker like so:

const worker = new Worker( new URL( "path/to/worker.js", import.meta.url ));

And an example of a Worker:

import { convenientFunction } from "./local/and/also/used/in/main/app-bundle";

self.addEventListener( "message", e => {
    // whatever Worker should do
});

When I bundle the app and load the Worker I get the following error in the console:

1.js:604 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:8080/js/js/node_modules_core-js_modules_es_error_cause_js.js' failed to load.

Which disappears when I remove the import. For the record I can import libraries from node_modules just fine, but for some reason it looks like local files also used by the main application bundle outside of the Worker lead to this error.

I feel like I'm overlooking something very obvious but from the spartan documentation on Workers I'm unsure where to look.

Igor Zinken
  • 884
  • 5
  • 19
  • I have eventually replaced my Webpack setup with Vite which works for me. The original question still stands unanswered... – Igor Zinken Mar 16 '23 at 20:46

1 Answers1

0

i don't think you can use import inside a normal JavaScript file you need a module file check if the answer of this one helps: Web Workers - How To Import Modules

net-js
  • 119
  • 1
  • 8
  • Well that's kinda what Webpack should solve: to bundle the modules in a way the browser can understand. Also, for `node_module`-imports it works... However I'm tempted to go for your suggestion as the target browsers for my application should support module based Workers. Still, going from `worker-loader` to the new Worker syntax in Webpack is definitely a step back... – Igor Zinken May 29 '22 at 20:55