使用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
相关产品推荐
相关产品推荐

