Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dandansoysauce opened this issue Jun 24, 2021 · 2 comments

Comments

@dandansoysauce
Copy link

dandansoysauce commented Jun 24, 2021

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
Copy link

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
Copy link

antoniocaiazzo commented May 4, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants