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

WebDriverIO自定义Reporter出现Cannot use import statement outside a module报错如何处理

错误原因

你遇到的Cannot use import statement outside a module报错是因为Node.js默认采用CommonJS模块规范,仅识别require/module.exports语法,你在reporter.js中使用的import/export default属于ES模块语法,文件被Node加载前没有经过Babel转译,因此触发语法错误。

验证Babel是否生效的方法
  • 手动执行转译验证:在项目根目录执行命令npx babel ./reporter/reporter.js --out-file babel-test-output.js,打开生成的babel-test-output.js文件,检查import语句是否被转换为require,export default是否被转换为module.exports。如果转换正常说明Babel本身配置无误,问题出在WDIO加载自定义reporter时未触发Babel转译;如果转换失败则说明Babel本身配置有问题。
  • 钩子加载验证:在WDIO配置文件的最顶部添加一行代码require('@babel/register'),之后运行测试,如果报错消失且自定义reporter的逻辑能正常执行,说明Babel转译已经生效。
可能遗漏的配置项
  • 未提前加载Babel转译钩子:WDIO默认仅会对测试用例文件做转译处理,不会自动转译自定义reporter这类外部引入的文件。你需要先安装Babel相关依赖:
    npm install @babel/core @babel/register @babel/preset-env --save-dev
    
    之后可以选择两种方式触发转译:要么在WDIO配置文件最顶部引入@babel/register,要么使用babel-node来启动WDIO命令。
  • Babel配置文件规则有误:检查项目根目录下的.babelrc或babel.config.json文件是否存在,且包含转译ES模块的配置,参考配置如下:
    {
      "presets": [["@babel/preset-env", { "targets": { "node": "current" } }]]
    }
    
    同时确认Babel配置的exclude字段没有排除你存放自定义reporter的目录。
  • 如果你不想额外配置Babel,也可以直接将reporter.js的语法改为CommonJS规范,修改后的代码如下:
    const WDIOReporter = require('@wdio/reporter').default;
    
    module.exports = class CustomReporter extends WDIOReporter {
        constructor(options) {
            options = Object.assign(options, { stdout: true })
            super(options)
        }
    
        onTestPass(test) {
            this.write(`Congratulations! Your test "${test.title}" passed 👏`)
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 12:36:04