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

Vue+Vite本地开发环境Web Worker报错:Cannot use import statement outside of a module

解决Vite Vue项目本地开发Web Worker的"Cannot use import statement outside a module"错误

以下是针对该问题的排查和解决步骤:

  • 升级Vite到稳定版本
    部分旧版Vite的worker配置与?worker&url后缀存在兼容性bug,建议升级到Vite 4.x及以上的稳定版本后重新测试。

  • 调整Worker导入方式
    尝试直接导入Worker实例而非仅URL,Vite会自动处理模块类型,避免手动配置可能引发的路径或类型冲突:

    import MyWorker from '@/libs/my.worker?worker'
    const worker = new MyWorker()
    
  • 确认Vite配置的正确性
    确保worker配置位于defineConfig的顶层,而非嵌套在build或其他选项中:

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    
    export default defineConfig({
      plugins: [vue()],
      worker: {
        format: 'es',
      }
    })
    
  • 清除Vite本地缓存
    本地开发的缓存可能导致旧的非模块Worker代码被加载,删除项目根目录下的node_modules/.vite文件夹,然后重启开发服务器。

  • 检查Worker文件及目录配置
    确保Worker文件内部仅使用ES模块语法(如import),无require等CommonJS语法;同时检查Worker所在目录是否存在package.json文件,若其中有type: "commonjs"字段,需删除或改为type: "module"。

  • 验证Worker实际加载内容
    在浏览器开发者工具的Network面板中找到Worker的请求,查看响应内容。若发现代码被转为CommonJS格式,说明Vite的Worker配置未生效,需重新检查配置位置或Vite版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:20:00