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

使用Playwright与TypeScript时导入自定义TS模块找不到的问题求助

在SvelteKit+Playwright+TypeScript环境中解决测试文件导入本地TS模块问题

问题场景

刚搭建了搭配Playwright和TypeScript的新版本SvelteKit项目,目录结构如下:

tests
  A.spec.ts
  B.ts

在A.spec.ts中尝试导入同目录的B.ts:

import { test, expect } from "@playwright/test";
import { mymodule } from './B';
// ...测试代码

执行npm run test(即playwright test)时触发错误:

Error: Cannot find module 'my\imported-module\path\tests\B' imported from A.spec.ts

但VS Code未检测到代码错误。(注:提问者提供了基础示例仓库用于复现问题)

解决方法

1. 显式添加文件扩展名

Playwright的测试运行环境对ES模块的解析可能要求显式指定.ts扩展名,修改导入语句为:

import { mymodule } from './B.ts';

2. 确保TypeScript配置包含测试目录

检查项目根目录的tsconfig.json,确认include字段包含tests目录,让TypeScript能正确识别测试目录下的文件:

{
  "include": ["src/**/*", "tests/**/*"],
  // 其他配置...
}

3. 验证Playwright配置与模块类型兼容性

如果项目使用ES模块(package.json中设置了"type": "module"),确保playwright.config.ts的配置适配ES模块:

  • 避免使用CommonJS语法(比如require)
  • 确认testDir配置指向正确的测试目录:
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  // 其他配置...
});

原因说明

VS Code基于项目的tsconfig.json进行代码检查,会自动补全模块解析规则;而Playwright测试运行时的模块解析逻辑更严格,尤其是在ES模块模式下,必须显式指定文件扩展名,否则会出现找不到模块的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:45:32