1

I'm trying to use "worker_threads" in my react-app for some cpu-intensive works. but react-app can't find "worker_threads" in node.js library.

Here is my code:

const {Worker} = require('worker_threads');
const path = require('path');

function fibonacci_worker(n) {
    return new Promise((resolve,reject) => {
      const w1 = new Worker(path.join(__dirname,'/fib.js'), { workerData: n });
      w1.on('message',e => resolve(e));
      w1.on('error',e => reject(e));
    });
}

"npm start" script throws following error: "Can't resolve 'worker_threads' in 'C:\path\to\fibonacci.js'"

  • node version: 12.13.0
  • react-scripts version: 3.2.0
4

1 回答 1

2

React uses Node.js for runtime tasks such as compilation. You cannot use built-in Node.js tools in the own React app, since the app uses the scope and tools of the browser.

You can find more information about the (unexisting) multithreading of the browser in the following question: Why doesn't JavaScript support multithreading?

于 2019-10-26T09:02:22.360 回答