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

