As I've written in the EDIT of my question above, I've found the solution here: https://github.com/facebookincubator/create-react-app/issues/1277
This is a working example:
// worker.js
const workercode = () => {
self.onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Received from main: ' + (e.data);
console.log('Posting message back to main script');
self.postMessage(workerResult);
}
};
let code = workercode.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
const blob = new Blob([code], {type: "application/javascript"});
const worker_script = URL.createObjectURL(blob);
module.exports = worker_script;
Then, in the file that needs to use the web worker:
import worker_script from './worker';
var myWorker = new Worker(worker_script);
myWorker.onmessage = (m) => {
console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…