Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the web workers files have to be inside my public folder of the React application?

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:

Working

This doesn't work and gives error:

(Uncaught SyntaxError: Unexpected token '<' (at worker.js:1:1))

Not Working

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");
like image 573
Petar Todorov Avatar asked Nov 27 '25 04:11

Petar Todorov


1 Answers

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

like image 145
Jayant Sharma Avatar answered Nov 29 '25 16:11

Jayant Sharma