'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. 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!



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahura-del
Solution 2 Edoardo Guzzi