Next.js Discord

Discord Forum

How to use WebWorker with turbopack?

Answered
Virginia Rail posted this in #help-forum
Open in Discord
Avatar
Virginia RailOP
I tired to use window.Worker, but have error:

TestWorker.ts
  onmessage = (e) => {
  console.log("[Thread: 0]: " + "Test")
}


page.tsx
useEffect(() => {
    let worker0 = new window.Worker(new URL('TestWorker.ts', import.meta.url));
    console.log("Main Thread");
    return () => worker0.terminate();
  }, [])


error:
Refused to execute script from 'http://localhost:3000/_next/static/media/TestWorker.7afdbfd6.ts' because its MIME type ('video/mp2t') is not executable.
Answered by Ray
can you try new Worker()?
View full answer

5 Replies

Avatar
can you try new Worker()?
Answer
Avatar
Virginia RailOP
Yep, thanks
Avatar
let me know if it works for you
Avatar
Virginia RailOP
I did some change:

page.tsx (Use filename without extension and put file in folder "src/workers/")
useEffect(() => {
    let worker0 = new Worker(new URL('../workers/TestWorker', import.meta.url));
    console.log("Main Thread");
    worker0.postMessage("Hello World");
    return () => worker0.terminate();
  }, [])


src/workers/testWorker.ts
onmessage = (e) => {
  console.log("[Thread: 0]: " + "Test");
  console.log(e);
}


Its working fine
Avatar
cool