我有一个名为
workerBuilder.js
的工人助手:
export function getWorker(worker) {
const code = worker.toString();
const blob = new Blob([`(${code})()`]);
return new Worker(URL.createObjectURL(blob), { type: 'module' });
}
然后我就有了这个
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');
};
};
现在,当我尝试在另一个函数中使用它时,如下所示:
const instance = getWorker(fileUploadWorker);
instance.postMessage({ file, filePath });
我在控制台中看到此错误:
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.
不确定问题出在哪里,但我怀疑导入不起作用?有什么想法吗?
我的目标是创建一个处理异步上传文件的工作线程,这样我就不必等待它完成。
您是否尝试显式设置 blob 的 MIME 类型?
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' });
}
这会显式地将 Blob 的 MIME 类型设置为“application/javascript”,这应该可以解决您遇到的错误。