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

Playwright是否支持共享仓库?跨仓库引入模块遇语法错误求助

Playwright跨仓库共享配置问题解决方案

Playwright完全支持跨仓库共享POM、工具函数这类代码,你遇到的SyntaxError: Cannot use import statement outside a module错误本质是两个仓库的模块系统配置不一致导致的。

问题根源

Repo1中使用了ES模块语法(import),说明它的package.json里大概率配置了"type": "module",Node.js会将其识别为ES模块。但Repo2的模块系统可能是默认的CommonJS,当引入Repo1的代码时,Node.js会把Repo1的ES模块代码当成CommonJS执行,从而抛出语法错误。

具体解决步骤

1. 统一两个仓库的模块系统

  • 方案A:将Repo2切换为ES模块
    在Repo2的package.json中添加"type": "module"字段:

    {
      "type": "module",
      // 其他配置...
    }
    

    同时确保Repo2中所有测试文件、配置文件(如playwright.config.ts)的模块语法与ES模块一致。

  • 方案B:让Repo1同时支持CommonJS和ES模块
    如果Repo2需要保留CommonJS,可以在Repo1的package.json中配置条件导出,同时生成两种格式的编译产物:

    {
      "type": "module",
      "main": "./dist/cjs/index.js",
      "module": "./dist/esm/index.js",
      "types": "./dist/types/index.d.ts",
      "exports": {
        ".": {
          "require": "./dist/cjs/index.js",
          "import": "./dist/esm/index.js"
        }
      }
    }
    

    对应的TypeScript配置(tsconfig.json)需要分别编译两种格式:

    {
      "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "outDir": "./dist/esm",
        "declarationDir": "./dist/types"
      },
      "include": ["src/**/*"]
    }
    

    再新增一个tsconfig.cjs.json:

    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "module": "CommonJS",
        "outDir": "./dist/cjs"
      }
    }
    

    最后在Repo1的package.json的scripts中添加编译命令:

    {
      "scripts": {
        "build": "tsc && tsc -p tsconfig.cjs.json"
      }
    }
    

2. 检查TypeScript配置(若使用TS)

确保两个仓库的tsconfig.json中compilerOptions.module字段保持一致:

  • 若用ES模块,设为ESNext或ES2020
  • 若用CommonJS,设为CommonJS

3. 确认本地依赖的正确性

如果是通过npm link或file:协议引入Repo1,需确保:

  • Repo1已经执行过npm run build(若为TS项目),生成了正确的编译产物
  • Repo1的package.json中main/module/exports字段指向了正确的入口文件

额外注意事项

Playwright Test本身支持ES模块和CommonJS,但需要确保playwright.config.ts的配置与项目模块系统匹配。例如,若使用ES模块,配置文件需用export default而非module.exports。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:15:43