Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Create Worker in React

Tags:

reactjs

worker

I'm trying to create a worker in an app created from create-react-app using react 16.8.6 and yarn 1.16.0. If I use const backgroundWorker = new Worker('../assets/js/myWorker.js');

I get the console error: Uncaught SyntaxError: Unexpected token <

But I know that is the correct path. This works fine in Angular. Is there a good tutorial on how to create a worker in React?

like image 984
mmclean Avatar asked Jun 21 '26 07:06

mmclean


1 Answers

The directory "assets" is the public directory for @angular/cli projects, not create-react-app projects. In create-react-app the equivalent of @angular/cli "assets" is "public" which is described in the create-react-app documentation under Using the Public Folder. Move your "js" directory and the "myWorker.js" file to the public directory and update the creation of the worker to point to that path instead:

const backgroundWorker = new Worker('/js/myWorker.js');

You can also use process.env.PUBLIC_URL instead:

const backgroundWorker = new Worker(`${process.env.PUBLIC_URL}/js/myWorker.js`);

Hopefully that helps!

like image 135
Alexander Staroselsky Avatar answered Jun 24 '26 02:06

Alexander Staroselsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!