Search code examples
javascriptreactjsweb-worker

Creating a Web Worker in React always gives an error


I am having the problem where every time i try to create a web worker returns the following error:

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

Here is the simple worker i am trying to create: worker.js

onmessage = function(e) {
    let message = e.data;
    console.log('Main thread said', message);
    postMessage('Hi!')
  }

App.js ...

  let worker = new Worker('worker.js')
  worker.postMessage('Hey!')
   
  worker.onmessage = function(e) {
    console.log('Worker thread says', e.data)
  }

...


Solution

  • put your worker.js file inside the public folder, then your WebWorker may be loaded properly.

    const worker = new Worker('worker.js');