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

Vue2+Jest单元测试报错:Cannot use import statement outside a module

解决Vue2/Jest测试中CKEditor引发的SyntaxError: Cannot use import statement outside a module
  • 调整transformIgnorePatterns规则,覆盖CKEditor全系列依赖
    你的现有规则只排除了@ckeditor开头的包,但CKEditor 5的很多子包是ckeditor5-前缀,需要把这些也加进去,确保Jest转译这些ES模块代码:

    transformIgnorePatterns: [
      '/node_modules/(?!(@ckeditor|ckeditor5-|ckeditor4-)).+\.(js|jsx|ts|tsx|vue)$'
    ]
    
  • 确认Jest的transform配置正确关联转译器
    确保JS和Vue文件都有对应的转译处理,避免漏转:

    transform: {
      '^.+\\.vue$': 'vue-jest',
      '^.+\\.js$': 'babel-jest'
    }
    
  • 配置Babel支持测试环境转译ES模块
    在你的Babel配置文件(.babelrc或babel.config.js)里,给测试环境添加@babel/preset-env,让Babel把ES模块转成Node能识别的CommonJS:

    {
      "env": {
        "test": {
          "presets": [
            ["@babel/preset-env", { "targets": { "node": "current" } }]
          ]
        }
      }
    }
    
  • 针对特定CKEditor模块添加模块映射(可选)
    如果还是有个别模块报错,试试用moduleNameMapper指定模块的入口文件,强制Jest加载转译后的版本:

    moduleNameMapper: {
      '^@ckeditor/ckeditor5-core$': '@ckeditor/ckeditor5-core/src/index.js',
      // 根据实际报错的模块路径调整
    }
    
  • 清理Jest缓存再重试
    有时候缓存会导致配置不生效,执行以下命令清空缓存后重新跑测试:

    jest --clearCache
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:40:36