[英]How to import a library into a web worker in React.js?
I am trying to run a face detection process in the background of my React app using a web worker.我正在尝试使用 web 工作程序在我的 React 应用程序的后台运行人脸检测过程。 I am using a library called face-api.js
to do the face detection.我正在使用一个名为face-api.js
的库来进行人脸检测。 But I'm unsure as to how to import this library to use in my worker.js
file.但我不确定如何导入这个库以在我的worker.js
文件中使用。
worker.js worker.js
import * as faceapi from 'face-api.js';
this.onmessage = (e) => {
console.log("Message from worker.js");
this.postMessage('Hello Main')
};
TestComponent.js测试组件.js
import React, {useEffect} from 'react'
function TestComponent() {
useEffect(() => {
const worker = new Worker('./workers/worker.js')
worker.postMessage('Hello Worker')
worker.onmessage = e => {
console.log('Message received from worker:', e.data)
}
}
);
return (
<div>
<h1> Test Component </h1>
</div>
)
}
export default TestComponent
I run this test code and I get the following error on chrome:我运行此测试代码,并在 chrome 上收到以下错误:
/workers/worker.js:1 Uncaught SyntaxError: Cannot use import statement outside a module
I have tried using require
to import the library which didn't work.我尝试使用require
导入不起作用的库。 I also tried declaring the worker as a module const worker = new Worker('./workers/worker.js', type: "module")
This makes the error go away but then nothing works: the worker does not do what it is intended to do.我还尝试将工作人员声明为模块const worker = new Worker('./workers/worker.js', type: "module")
这使得错误 go 消失但没有任何作用:工作人员没有做它是什么打算做的。
Please point me in the right direction.请指出我正确的方向。 Thanks in advance!提前致谢!
I guess you should use importScript()
in your service worker file我想你应该在你的服务工作者文件中使用importScript()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.