Webpack v5 has built-in support for web workers, initialized in the following format:
const worker = new Worker(new URL("./worker.js", import.meta.url));
While working on a Next.js (with webpack v5) project, I noticed that a slight variation of the above breaks down:
const url = new URL("./worker.js", import.meta.url);
const worker = new Worker(url);
This leads to the following error on the browser console:
SyntaxError: import declarations may only appear at top level of a module
which occurs because (and only when) I’m importing something in the worker file.
Here’s a minimal reproduction of the above. Instructions to run and the lines to look at are in the README.
Why does this happen? How does defining the worker URL in a separate variable change things?