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

Playwright+Cucumber集成Lighthouse遇ESM导入错误求助

Playwright+Cucumber集成Lighthouse时的ESM导入错误解决方法

遇到的错误

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Playwright\node_modules\playwright-lighthouse\index.js from C:\Playwright\src\pages\example\exampleHomePage.ts not supported.
Instead change the require of index.js in C:\Playwright\src\pages\example\exampleHomePage.ts to a dynamic import() which is available in all CommonJS modules.

已尝试在ExampleHomePage的navigateToHomePage1方法中使用动态import引入playwright-lighthouse,但错误仍触发。

项目相关代码

Feature文件

Feature: Lighthouse
  @lighthouse @ui
  Scenario: Evaluate the performance of the homepage
    Given I am on the homepage
    When I run Lighthouse test
    Then Lighthouse should generate a performance results

StepDef文件

import { LoggerManager, fixture } from "../../../hooks/pageFixture";
import { Given, When, Then } from "@cucumber/cucumber";

import exampleHomePage from "../../../pages/example/exampleHomePage";

let examplePage: exampleHomePage;

Given(`I am on the homepage`, async () => {
  examplePage = new exampleHomePage(fixture.page)
  const response = await examplePage.navigateToHomePage1();
});
 
When(`I run Lighthouse test`, async function () {
    // [When] Describes the action or event that triggers the scenario.
});

Then(`Lighthouse should generate a performance results`, async function () {
    // [Then] Describes the expected outcome or result of the scenario.
});

ExampleHomePage文件

import { Page } from "@playwright/test";


export default class ExampleHomePage {
    private base: baseObjects;
    private assert: pageAssertion;
    private testDataManager = new TestDataManager();

    constructor(private page: Page) {
        this.base = new baseObjects(page);
        this.assert = new pageAssertion(page);
    }

    private Elements = {

    }

    async navigateToHomePage1() {
        // Importing 'playwright-lighthouse' using dynamic import
        const { playAudit } = await import('playwright-lighthouse');
        
        // Assuming this.base.navigateToHome1 is defined elsewhere in your code
        this.base.navigateToHome1('https://www.google.co.uk/');
    
        // Invoking playAudit function
        await playAudit({
            page: this.page,
            port: 9222,
            thresholds: {
                performance: 50,
                accessibility: 50,
                'best-practices': 50,
                seo: 50,
                pwa: 50,
            },
            reports: {
                formats: {
                    html: true,
                },
                name: `lighthouse-${new Date().toISOString()}`,
                directory: `${process.cwd()}/lighthouse`,
            },
        });
    }
}

解决方法

1. 配置项目为ESM模块

在项目根目录的package.json中添加或修改type字段:

{
  "type": "module"
}

注意:此修改会将整个项目切换为ESM模式,需将所有require()调用替换为import语法,若仍需保留部分CommonJS文件,可将其扩展名改为.cjs。

2. 调整TypeScript编译配置

修改tsconfig.json,确保编译输出为ESM格式:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "node",
    "target": "ES2020",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

3. 修正Cucumber运行配置

修改cucumber.json配置文件,指定使用ESM加载器:

{
  "default": {
    "requireModule": ["ts-node/register/esm"],
    "require": ["src/**/*.ts"]
  }
}

运行Cucumber时添加Node.js ESM兼容参数:

npx cucumber-js --experimental-specifier-resolution=node

4. 排查隐性CommonJS引用

检查项目中是否有其他文件通过require直接或间接引入playwright-lighthouse或其依赖模块,全部替换为动态import或ESM的import语法。

5. 备选方案:直接使用Lighthouse原生API

若第三方封装库playwright-lighthouse的ESM兼容问题无法解决,可直接调用Lighthouse原生API配合Playwright:

import lighthouse from 'lighthouse';
import { URL } from 'url';

async function runLighthouseAudit(page) {
  const session = await page.context().newCDPSession(page);
  const { port } = session;
  
  const { lhr, report } = await lighthouse(new URL(page.url()).href, {
    port,
    output: 'html',
    thresholds: {
      performance: 50,
      accessibility: 50,
      'best-practices': 50,
      seo: 50,
      pwa: 50,
    }
  });

  // 保存报告到本地
  const fs = await import('fs/promises');
  await fs.writeFile(`${process.cwd()}/lighthouse/lighthouse-${new Date().toISOString()}.html`, report);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:12:47