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

TypeScript+Playwright运行测试报Cannot find module '@common/common'如何解决

解决Playwright运行测试时找不到@common/common模块问题

错误原因

你在tsconfig.json中配置了@common/*这类路径别名,但Playwright Test运行器默认不会自动加载tsconfig的paths配置,导致别名无法被正确解析,触发MODULE_NOT_FOUND报错。

解决步骤

  • 第一步:确认基础文件路径正确
    首先检查项目根目录下是否存在src/common/common.ts(也可以是js、tsx等TS可识别的后缀文件),和tsconfig中配置的"@common/*": ["src/common/*"]映射规则匹配,文件不存在的话先创建对应文件。
    同时确认src/common/common.ts的导出规则和导入写法匹配:如果是默认导出则用import Common from '@common/common',如果是命名导出则改为import { Common } from '@common/common'。

  • 第二步:配置Playwright识别路径别名,二选一即可:

方案1:修改playwright.config.ts配置别名

在项目根目录的playwright配置文件中添加别名映射:

import { defineConfig } from '@playwright/test';
import path from 'path';

export default defineConfig({
  // 保留你原有的其他配置,比如测试目录、浏览器配置等
  resolve: {
    alias: {
      '@common': path.resolve(__dirname, 'src/common'),
      '@config': path.resolve(__dirname, 'tests/config'),
    },
  },
});

方案2:修改测试启动命令注册路径解析

你已经安装了tsconfig-paths依赖,直接修改package.json中的test脚本,运行测试前先注册别名解析:

{
  "scripts": {
    // 其他原有脚本不变
    "test": "node -r tsconfig-paths/register ./node_modules/@playwright/test/cli.js test"
  }
}
  • 第三步:修复tsconfig语法问题(可选)
    你当前贴出的tsconfig.json中paths配置的最后一项末尾多了多余的逗号,部分低版本TS会解析失败,建议删掉:
"paths": {
  "@config/*": [
    "tests/config/*"
  ],
  "@common/*": [
    "src/common/*"
  ] // 删掉这里的多余逗号
}

修改完成后重新运行npm run test即可正常识别别名。

内容的提问来源于stack exchange,提问作者안성민

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:09:03