-1

I have the worker helper in react called workerBuilder.js:

export function getWorker(worker) {
  const code = worker.toString();
  const blob = new Blob([`(${code})()`]);
  return new Worker(URL.createObjectURL(blob), { type: 'module' });
}

I then have this fileUploadWorker.js:

import { uploadFile } from 'utilities/storage.utils';
import { STORAGE_BUCKET_ENUM } from 'models/application/enums/ImageEnums';

export default () => {
  self.onmessage = async (message) => {
    const result = await uploadFile(message.data.file, STORAGE_BUCKET_ENUM.ATTACHMENTS, message.data.filePath);
    if (!result) {
      postMessage('Could not upload');
      return;
    }

    postMessage('File uploaded');
  };
};

Now when I try to use it in another function, like this:

const instance = getWorker(fileUploadWorker);

instance.postMessage({ file, filePath });

I see this error in console:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Not sure where the problem lies, but I suspect the imports don't work? Any ideas?

My goal is to create a worker that handles uploading files async so I don't have to wait for it to complete.

3

1 Answer 1

0

Did you try to explicitly set the MIME type for your blob ?

export function getWorker(worker) {
  const code = worker.toString();
  const blob = new Blob([`(${code})()`], { type: 'application/javascript' }); // Explicitly set the MIME type
  return new Worker(URL.createObjectURL(blob), { type: 'module' });
}

This explicitly sets the MIME type of the Blob to 'application/javascript', which should probably resolve the error you're encountering.

Sign up to request clarification or add additional context in comments.

2 Comments

yep, just tried and now it says ncaught (in promise) ReferenceError: utilities_storage_utils_ts__WEBPACK_IMPORTED_MODULE_0__ is not defined but its prob as mentioned that i cant import typescript files?
Yes, by default, web workers don't have built-in support for TypeScript. You'll need to transpile your TypeScript code into JavaScript first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.