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

Playwright-Lighthouse测试中TypeScript导入JSON遇ESM兼容问题

无法在Playwright-Lighthouse测试中导入JSON字符串数组

问题详情

我在Playwright-Lighthouse性能测试中尝试导入JSON格式的URL数组时,遇到了模块兼容错误,具体情况如下:

测试代码

import { test, expect, chromium } from '@playwright/test';
import { playAudit } from 'playwright-lighthouse';
import { thresholds } from '../../config/thresholds';
import * as URLs from '../../config/urls.json'

URLs.forEach(url => {
  test(`Ligthouse performance test for ${url}`, async () => {
      const browser = await chromium.launch({
          args: ['--remote-debugging-port=9222'],
          headless: false
      });
      const page = await browser.newPage();
      await page.goto(url);
      await playAudit({
          page: page,
          thresholds: thresholds,
          port: 9222,
          reports: {
              formats: {
                  html: true, //defaults to false
              },
              name: `ligthouse-${new Date().toISOString()}`, //defaults to `lighthouse-${new Date().getTime()}`
              directory: `${process.cwd()}/lighthouse`, //defaults to `${process.cwd()}/lighthouse`
          },
      });
      await page.close();
      await browser.close();
  })
});

错误信息

鼠标悬停在导入错误上时显示:

Error: require() of ES Module /Users/duane.hodges/projects/PERFORMANCE-TESTS/node_modules/lighthouse/core/index.js from /Users/duane.hodges/projects/PERFORMANCE-TESTS/node_modules/playwright-lighthouse/src/task.js not supported.
Instead change the require of index.js in /Users/duane.hodges/projects/PERFORMANCE-TESTS/node_modules/playwright-lighthouse/src/task.js to a dynamic import() which is available in all CommonJS modules.playwright

尝试将导入方式改为import { URLs } from '../../config/urls.json';后,测试可启动,但运行时仍报错:

PERFORMANCE-TESTS % npx playwright test "home.spec.ts" -g "Ligthouse\s+performance\s+test\s+for\s+(.*?)$"
Error: require() of ES Module /projects/PERFORMANCE-TESTS/node_modules/lighthouse/core/index.js from /projects/PERFORMANCE-TESTS/node_modules/playwright-lighthouse/src/task.js not supported.
Instead change the require of index.js in //projects/PERFORMANCE-TESTS/node_modules/playwright-lighthouse/src/task.js to a dynamic import() which is available in all CommonJS modules.

   at performance/home.spec.ts:4

  2 | import { playAudit } from 'playwright-lighthouse';
  3 | import { thresholds } from '../../config/thresholds';
> 4 | import { URLs } from '../../config/urls.json';

已尝试的无效方案

按照网上建议创建tsconfig.json并添加resolveJsonModule配置,未解决问题:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
    },
    "resolveJsonModule": true
  }
}

解决方法

1. 修复模块兼容性冲突

错误核心是playwright-lighthouse用CommonJS语法导入了ES模块格式的lighthouse,导致模块系统不兼容,可通过以下两种方式解决:

方案一:切换项目为ES模块类型

  • 在项目根目录package.json中添加:
    {
      "type": "module"
    }
    
  • 更新tsconfig.json配置,确保TypeScript输出ES模块:
    {
      "compileOnSave": false,
      "compilerOptions": {
        "baseUrl": "./",
        "resolveJsonModule": true,
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "target": "ES2020"
      }
    }
    

方案二:修改playwright-lighthouse的导入逻辑

如果不想改动项目模块类型,可修改node_modules/playwright-lighthouse/src/task.js中导入lighthouse的代码:
将原CommonJS导入:

const lighthouse = require('lighthouse');

替换为ES模块动态导入:

// 使用async/await方式
const { default: lighthouse } = await import('lighthouse');

若要持久化修改,可使用patch-package工具记录该修改,避免依赖包更新后失效。

2. 修正JSON导入语法

确保你的urls.json是数组格式,例如:

["https://example.com", "https://test.example.com"]

导入时使用默认导出语法(因为JSON数组属于默认导出,而非命名导出):

import URLs from '../../config/urls.json';

内容的提问来源于stack exchange,提问作者D.Hodges

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:02:39