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

Deno报错Classic workers are not supported,如何从字符串动态创建Web Worker?

报错原因

Deno默认仅支持ES Module类型的Worker,未实现传统的classic(经典脚本)类型Worker。你直接通过Blob URL创建Worker时,默认会被识别为classic类型,因此触发Classic workers are not supported报错。

解决方案

你可以继续使用动态字符串生成Worker,仅需在创建Worker时明确指定type: "module"参数即可,不需要依赖本地静态文件。

可运行示例代码如下:

// 动态构造Worker内的执行逻辑,可在运行时任意拼接
const workerRuntimeCode = `
// Worker内部逻辑
self.onmessage = (event) => {
  const result = \`处理完成,传入参数为:\${event.data}\`
  self.postMessage(result)
}
`

const blob = URL.createObjectURL(
  new Blob([workerRuntimeCode], { type: 'text/javascript' })
)

// 初始化时明确指定module类型
const worker = new Worker(blob, {
  type: "module",
  // 若需要在Worker中使用Deno内置API(如文件读写等),可开启此配置
  // deno: true
})

// 测试通信
worker.postMessage("测试动态Worker")
worker.onmessage = (event) => {
  console.log(event.data)
  worker.terminate()
  URL.revokeObjectURL(blob)
}

注意事项

  • 如果开启了deno: true配置,启动主脚本时需要添加对应的权限参数,比如deno run --allow-read main.js。
  • 不再使用的Worker要调用terminate()释放资源,不再需要的Blob URL可以调用URL.revokeObjectURL()清理内存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:03