GoogleChromeLabs / worker-plugin

👩‍🏭 Adds native Web Worker bundling support to Webpack.
https://npm.im/worker-plugin
Apache License 2.0
1.91k stars 79 forks source link

Webpack 5: import declarations may only appeaar at the top level of a module #105

Open dandansoysauce opened 3 years ago

dandansoysauce commented 3 years ago

For some reason, I can't import anything on my worker file.

SyntaxError: import declarations may only appear at top level of a module

I have this simple worker:

import { InitMe } from "../lib/Helper";

addEventListener("message", event => {
    console.log(event.data);
})

being called here:

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

Commenting out the import line will make it work.

mkamalkayani commented 2 years ago

I am also getting exactly same error. I am using nextjs 12 with default webpack config. I also tried

const worker = new Worker(new URL("./test.worker.js", import.meta.url), { type: 'module' }); but it also did't work.

Tested it on: Chrome: 96.0.4664.93 (Official Build) (x86_64) Firefox: 95.0 (64-bit)

@dandansoysauce would you kindly share your solution.

antoniocaiazzo commented 2 years ago

A bit late for my reply, and also not much of a solution, but I've found that the only way for web Workers to actually work in Next.js and Webpack is to respect as closely as possible this example: https://github.com/vercel/next.js/tree/canary/examples/with-web-worker (the .babelrc file is not necessary).

Admittedly I don't know the reasons behind it (still starting out with Next.js and Webpack).

If for example you store import.meta.url in a variable you get an opaque error like:

Security Error: Content at http://localhost:3000/ may not load data from file:///...../with-web-worker-app/worker.js.

Which happened during some tests and took some time to track down. And also if you try to create the Worker object in a separate function (say for a factory pattern) passing in the URL object as a parameter, you get another unrelated error:

SyntaxError: import declarations may only appear at top level of a module

Waiting for someone with more experience to shed some light on this.