Playwright+TypeScript测试构建失败:模块导入找不到求助
我执行npm init playwright@latest,指定src/tests为测试目录、typescript为开发语言,未修改playwright.config.ts。随后创建src/tests/e2e.spec.ts文件,VSCode对代码无报错,但运行npx playwright test时提示找不到导入模块,报错信息显示无法找到../worker/messages路径。
项目文件夹结构
├── package.json ├── playwright.config.ts ├── tsconfig.json ├── webpack.config.js └── src ├── messages.ts ├── tests │ ├── e2e.spec.ts │ └── fixtures.ts └── worker └── messages.ts
更新1:给导入路径添加.ts后缀后,Playwright不再报错,但依赖文件的所有导入都需加.ts,无法批量修改,寻求根源解决办法。
更新2:附上tsconfig.json配置:
{ "compilerOptions": { "strict": true, "module": "commonjs", "target": "es6", "esModuleInterop": true, "sourceMap": true, "rootDir": "./src", "outDir": "dist/js", "noEmitOnError": true, "typeRoots": [ "node_modules/@types" ] }, "exclude": ["playwright.config.ts"] }
解决方案
1. 为Playwright测试单独配置TypeScript
你的根目录tsconfig.json是针对生产代码编译到dist/js的配置,而Playwright运行测试时不需要编译输出,直接加载源码,两者的模块解析逻辑冲突。可以在src/tests下创建专属的tsconfig.json:
{ "extends": "../../tsconfig.json", "compilerOptions": { "rootDir": "../../src", "moduleResolution": "node", "baseUrl": "../../src", "noEmit": true, // 测试代码无需编译输出 "paths": { "*": ["*"] } }, "include": ["./**/*.ts"] }
然后在playwright.config.ts中指定这个配置文件:
import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: './src/tests', // 配置Playwright使用测试专属的tsconfig typescript: { tsconfigPath: './src/tests/tsconfig.json', }, // 其他原有配置... });
2. 调整根目录tsconfig的模块解析规则
如果不想单独配置,直接修改根目录tsconfig.json,补充模块解析相关配置,让TypeScript和Playwright的解析逻辑一致:
{ "compilerOptions": { "strict": true, "module": "commonjs", "target": "es6", "esModuleInterop": true, "sourceMap": true, "rootDir": "./src", "outDir": "dist/js", "noEmitOnError": true, "typeRoots": [ "node_modules/@types" ], "moduleResolution": "node", // 明确使用Node模块解析规则 "baseUrl": "./src", // 设置基准路径为src目录 "paths": { "*": ["*"] } // 映射所有模块路径到src下 }, "exclude": ["playwright.config.ts"], "include": ["src/**/*.ts"] // 确保包含所有src下的TypeScript文件 }
修改后,Playwright会自动读取更新后的配置,无需额外修改playwright.config.ts。
3. 验证路径正确性
确认e2e.spec.ts中的导入路径../worker/messages确实对应src/worker/messages.ts,没有拼写错误或目录层级错误——VSCode能识别是因为它依赖tsconfig的路径映射,而Playwright之前没正确读取到配置才会报错。
内容的提问来源于stack exchange,提问作者JobaDiniz

