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

Cypress 13.5报错:Cannot use import statement outside a module 求助

解决Cypress测试中"Cannot use import statement outside a module"错误

问题重现

运行以下Cypress测试代码时抛出错误:

describe('Login to Tabaq', () => {
    it('Login Valid Test', () => {
      cy.visit('https://tabaq.ae/Login/index')
    })
})

错误信息:

SyntaxError: 以下错误源自您的应用代码,而非Cypress。
Cannot use import statement outside a module

已在package.json中设置"type": "module",但问题仍未解决。


解决方案

1. 升级Cypress到支持ES模块的版本

Cypress 12及以上版本对ES模块的支持更完善,如果你的版本较低,执行以下命令升级:

npm install cypress@latest --save-dev

2. 配置Cypress启用ES模块检测

在项目根目录的cypress.config.js(或cypress.config.mjs)中添加实验性模块检测配置:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',
    // 启用ES模块自动检测
    experimentalModuleDetection: true,
  },
})
  • 如果你的package.json已设置"type": "module",确保Cypress配置文件使用.js后缀;若未设置,可将配置文件改为.mjs后缀。

3. 检查测试文件及依赖的导入格式

  • 确保测试文件中的导入语句使用ES模块语法(import ... from ...),而非CommonJS的require
  • 注意:Cypress会全局注入describe、it、cy等API,无需手动导入这些核心方法

4. 排查Babel/Webpack配置冲突

如果项目使用Babel或Webpack,需确保它们的配置支持ES模块:

  • Babel:在.babelrc或babel.config.json中设置modules: false
    {
      "presets": [
        ["@babel/preset-env", { "modules": false }]
      ]
    }
    
  • Webpack:在配置文件的output中添加module: true
    module.exports = {
      output: {
        module: true,
      },
    }
    

5. 清除Cypress缓存后重试

缓存可能导致配置不生效,执行以下命令清除缓存后重新运行测试:

npx cypress cache clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:17:16