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.
Did you try to explicitly set the MIME type for your blob ?
This explicitly sets the MIME type of the Blob to 'application/javascript', which should probably resolve the error you're encountering.