How to import a library into a web worker in React.js?
Asked Answered
N

2

7

I am trying to run a face detection process in the background of my React app using a web worker. I am using a library called face-api.js to do the face detection. But I'm unsure as to how to import this library to use in my worker.js file.

worker.js

    import * as faceapi from 'face-api.js';
    
    this.onmessage = (e) => {
      console.log("Message from worker.js");
      this.postMessage('Hello Main')   
    };

TestComponent.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:

 /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. 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.

Please point me in the right direction. Thanks in advance!

Nonce answered 8/1, 2021 at 8:59 Comment(4)
Have you tried using Worker-loader as a webpack plugin for your web-worker?Apus
Have you solved this? I run into the same issueFibrovascular
Did you try to use useWorker library?Kashmiri
@Nonce you need to write something like that const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });Liberal
L
1

you need to use {type:"module"} in the options of worker constructor for use "import" features in the worker file.

https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker

options Optional An object containing option properties that can be set when creating the object instance. Available properties are as follows:

type: A DOMString specifying the type of worker to create. The value can be classic or module. If not specified, the default used is classic.

credentials: A DOMString specifying the type of credentials to use for the worker. The value can be omit, same-origin, or include. If not specified, or if type is classic, the default used is omit (no credentials required).

name: A DOMString specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.

Liberal answered 22/2, 2022 at 13:25 Comment(0)
M
0

I guess you should use importScript() in your service worker file

Mannino answered 11/12, 2021 at 7:12 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Valene

© 2022 - 2024 — McMap. All rights reserved.