You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web Worker以module类型加载模块脚本失败问题排查

解决Worker模块脚本MIME类型错误及import无法解析问题

问题原因

  1. 动态Blob生成的Worker无法解析import:通过worker.toString()将带import的worker函数转成字符串生成Blob时,打包工具(如Webpack/Vite)不会处理这种动态生成代码里的import语句,Worker无法找到对应的模块资源。
  2. Blob未指定正确MIME类型:创建Blob时未设置type: 'application/javascript',导致Blob URL返回的MIME类型为空,触发模块脚本的严格MIME检查错误。

解决方案

方案一:直接加载打包后的Worker文件(推荐)

这种方式让打包工具正常处理Worker的依赖解析,是最可靠的方案:

  1. 修改fileUploadWorker.js,去掉默认导出的函数,直接编写Worker逻辑:
import { uploadFile } from 'utilities/storage.utils';
import { STORAGE_BUCKET_ENUM } from 'models/application/enums/ImageEnums';

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');
};
  1. 在使用Worker的地方,通过new URL让打包工具识别Worker文件路径:
// 基于当前模块的URL构建Worker文件的绝对路径
const workerUrl = new URL('./fileUploadWorker.js', import.meta.url);
const instance = new Worker(workerUrl, { type: 'module' });

instance.postMessage({ file, filePath });

方案二:动态Blob方式(仅适合无外部依赖场景)

如果必须使用动态生成Blob的方式,需要解决MIME类型和依赖内联问题:

  1. 修正getWorker的Blob创建代码,指定正确MIME类型:
export function getWorker(worker) {
  const code = worker.toString();
  // 明确指定Blob的MIME类型为JavaScript模块
  const blob = new Blob([`(${code})()`], { type: 'application/javascript' });
  return new Worker(URL.createObjectURL(blob), { type: 'module' });
}
  1. 内联Worker的依赖代码(因为动态Blob无法访问外部模块):
// 先将依赖的函数和枚举转为可执行的字符串
const uploadFileCode = uploadFile.toString();
const STORAGE_BUCKET_ENUM_CODE = `const STORAGE_BUCKET_ENUM = ${JSON.stringify(STORAGE_BUCKET_ENUM)}`;

export default () => {
  // 注入依赖到Worker上下文
  eval(STORAGE_BUCKET_ENUM_CODE);
  const uploadFile = eval(`(${uploadFileCode})`);

  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');
  };
};

注意:此方案使用eval存在安全风险,且依赖代码内联会增加代码体积,仅适合简单场景,不推荐生产环境使用。


内容的提问来源于stack exchange,提问作者strangeQuirks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:55:28