I've ran into a problem trying to understand how web workers might be used inside React apps: Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1) I did a research on StackOverflow and found out that this problem could be solved just by moving the web worker file to the public folder of my React app. Can someone explain why did it worked?
This works:

This doesn't work and gives error:
(Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1))

The code (I don't think it matters but anyway):
//App.js
import React from "react";
const App = () => {
console.log("hey");
const worker = new Worker("worker.js");
return <div>App</div>;
};
export default App;
//worker.js
console.log("work");
You can try this, it works for me by giving relative path of the worker file:
const worker = new Worker("./worker3.js") // Unexpected token '<' (at worker3.js:1:1)
const worker = new Worker("src/components/web-worker/worker3.js") // works
or you can import your worker script by exporting it as Blob
Refer: https://codesandbox.io/p/sandbox/web-worker-reactjs-2sswe?file=%2Fsrc%2Fworker.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With