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

Cucumber+Playwright复用playwright.config.ts配置及模块错误解决

解决Cucumber + Playwright ES模块冲突并复用Playwright配置

核心问题

你的项目启用了ES模块(package.json中"type":"module"),但Cucumber默认用require()加载CommonJS模块,导致模块加载冲突报错。同时需要调整配置让Cucumber支持ES模块,并正确复用Playwright的slowMo、超时等配置。

具体解决方案

1. 修改Cucumber运行命令:用--import替代--require

报错明确提示用--import代替--require,因为--require会触发require()调用,不兼容ES模块。调整后的命令如下:

node --no-warnings=ExperimentalWarning --loader ts-node/esm node_modules/@cucumber/cucumber/bin/cucumber-js --import src/tests/**/*.ts

如果需要指定Cucumber配置文件,建议用.cjs后缀(避免ES模块冲突),比如cucumber.cjs,命令追加--config cucumber.cjs即可。

2. 在package.json中配置测试脚本

把上述命令封装成npm脚本,方便执行:

{
  "scripts": {
    "test:e2e": "node --no-warnings=ExperimentalWarning --loader ts-node/esm node_modules/@cucumber/cucumber/bin/cucumber-js --import src/tests/**/*.ts --config cucumber.cjs"
  }
}

3. 复用Playwright配置

在Cucumber的hooks或步骤定义中,通过ES模块导入playwright.config.ts,并在启动浏览器时传入配置项:

// 比如在hooks.ts中
import { Before, After } from '@cucumber/cucumber';
import { chromium } from '@playwright/test';
import playwrightConfig from '../../playwright.config.ts';

let browser;

Before(async () => {
  // 复用playwright.config.ts中的slowMo、超时等配置
  browser = await chromium.launch({
    slowMo: playwrightConfig.use?.slowMo,
    timeout: playwrightConfig.use?.timeout,
    // 其他需要复用的配置,比如headless等
  });
});

After(async () => {
  await browser.close();
});

注意:ES模块导入必须带完整文件后缀(比如.ts),不能省略。

4. 检查并修正tsconfig.json配置

确保TypeScript编译选项适配ES模块:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "node16", // 或"bundler",适配ES模块解析
    "target": "ES2020",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"]
}

5. 避免CommonJS切换问题

不要移除package.json中的"type":"module",否则会触发你提到的导出问题。保持ES模块配置,通过上述步骤让Cucumber适配即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:33