dnm*_*nmh 5 web-worker reactjs webpack create-react-app
I am working on a React app created with create-react-app. I was having trouble creating a web worker in it so I posted a question here on SO: Creating a web worker inside React
I've found a solution, as written in the post above, to load a worker without ejecting the app and messing with the Webpack config. This is the code, from the post above:
// worker.js
const workercode = () => {
self.onmessage = function(e) {
console.log('Message received from main script');
const 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;
Run Code Online (Sandbox Code Playgroud)
and in the file that uses the worker:
import worker_script from './worker';
const myWorker = new Worker(worker_script);
myWorker.onmessage = (m) => {
console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');
Run Code Online (Sandbox Code Playgroud)
It works, however, I cannot seem to get importScripts to work. Even if I do this (outside onmessage or inside onmessage):
if (typeof importScripts === 'function') {
importScripts('myscript.js');
}
Run Code Online (Sandbox Code Playgroud)
In that case, the if statement turns out to be true, but then fails on the actual import with the same error message 'importScripts' is not defined
as if the if statement is a false positive, which doesn't sound right. I'd say this is a context issue and that the worker probably isn't loading properly (although it seems to work), but it's just a guess.
Any ideas what's happening here?
小智 0
importScripts
在从 Blob 创建的工作线程中工作得很好,至少在 2021 年(react 17.0.2、react-scripts 4.0.3、Chrome 92)。导入的脚本 URL 必须是绝对的,因为工作程序是从 Blob 创建的。
最初的问题可能是 webpack 中的错误,或者转译可能以奇怪的方式更改了代码。
\nconst workercode = () => {\n importScripts("https://example.com/extra.js");\n console.log(self.extraValue); // 10\n\n self.onmessage = function(e) {\n console.log('Message received from main script');\n ...\n }\n};\n
Run Code Online (Sandbox Code Playgroud)\n\xc2\xa0
\n// extra.js\nself.extraValue = 10;\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
1597 次 |
最近记录: |