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

更新NPM包后Playwright无法动态导入JSON文件的问题

解决方案:Playwright更新后动态导入JSON报错问题

问题背景

更新Playwright依赖后,动态导入JSON文件出现TypeError: Module "xxx.json" needs an import attribute of "type: json",添加导入属性后又触发SyntaxError: 未启用实验性语法'importAttributes'的错误。

可行解决方案

方案1:改用Node.js fs模块读取JSON(推荐,无实验性语法依赖)

直接通过文件系统读取并解析JSON,避开ESM动态导入的语法限制:

import fs from 'fs/promises';
import path from 'path';

test('get started link', async ({ page }) => {
  // 拼接JSON文件的绝对路径
  const jsonPath = path.resolve(__dirname, './mouse.json');
  // 读取并解析JSON内容
  const mouse = JSON.parse(await fs.readFile(jsonPath, 'utf8'));
  console.log(mouse.mouse.name); // 输出 Jerry
});

方案2:配置Playwright启用实验性导入属性语法

如果坚持使用动态导入,需调整Playwright配置以支持Node.js的实验性语法:

  1. 修改playwright.config.js,添加nodeOptions启用实验性导入属性:
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  // 其他原有配置...
  nodeOptions: {
    experimentalImportAttributes: true,
  },
});
  1. 使用符合Node.js最新提案的导入语法(替换旧的assert为with):
test('get started link', async ({ page }) => {
  const mouse = await import('./mouse.json', { with: { type: 'json' } });
  console.log(mouse.default.mouse.name); // 注意ESM导入JSON会包裹在default字段中
});

方案3:改用CommonJS的require语法

若项目未强制使用ESM,可直接用require加载JSON(无需额外配置):

test('get started link', async ({ page }) => {
  const mouse = require('./mouse.json');
  console.log(mouse.mouse.name); // 输出 Jerry
});

注:如果项目package.json中设置了"type": "module",需将测试文件后缀改为.cjs才能使用require。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:59:52