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

使用Jest运行时遇「Cannot use import statement outside」ESM包错误求助

排查Jest运行「Cannot use import statement outside」错误的方向

你在Vite React项目中使用auto-animate包时遇到Jest测试报错「Cannot use import statement outside」,这通常是因为Jest默认使用CommonJS模块系统,而auto-animate是纯ES模块,导致环境不兼容。可以从以下几个方向排查:

  • 调整Jest配置对ES模块的支持
    在jest.config.js中添加或修改相关配置:

    1. 配置transformIgnorePatterns,让Jest转译node_modules中的auto-animate包:
      module.exports = {
        // 其他配置
        transformIgnorePatterns: ['/node_modules/(?!@formkit/auto-animate)/']
      }
      
    2. 若使用Jest 28+,启用ES模块支持:
      module.exports = {
        extensionsToTreatAsEsm: ['.js', '.jsx', '.ts', '.tsx'],
        moduleNameMapper: {
          '^(\\.{1,2}/.*)\\.js$': '$1'
        }
      }
      
    3. 尝试使用--experimental-vm-modules参数运行Jest,开启Node.js的ES模块支持。
  • 检查Babel配置
    若使用babel-jest,确保babel.config.json中测试环境的配置正确转换ES模块:

    {
      "env": {
        "test": {
          "presets": [
            ["@babel/preset-env", {"modules": "commonjs"}],
            "@babel/preset-react"
          ]
        }
      }
    }
    
  • 确认项目模块类型配置
    若项目package.json中设置了"type": "module",需要同步调整Jest配置以适配ES模块环境:

    • 将Jest的testEnvironment设置为'node'
    • 在运行Jest时添加--experimental-vm-modules参数
  • 验证auto-animate的导入与版本

    1. 确认导入语句正确:import autoAnimate from '@formkit/auto-animate'(注意包名是@formkit/auto-animate而非auto-animate)
    2. 查看auto-animate的版本,确保使用的是稳定版,避免版本兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:46:13