Playwright引入内部npm包报错:SyntaxError: Unexpected token 'export'
解决内部npm包导入时的
SyntaxError: Unexpected token 'export'问题 问题描述
我开发了一个供内部使用的npm包,里面包含测试复用代码,已经发布到内部源并成功安装到一个用Playwright做测试的项目里。但从这个包导入内容时,出现了错误:SyntaxError: Unexpected token 'export'。
项目用的是Node.js 20 + TypeScript,已经装了Babel并配置了相关预设,tsconfig里设置了"module": "ESNext",但问题依然存在。我的npm包用了同样的配置,不知道哪里漏了。
现有配置
tsconfig.json
{ "compilerOptions": { "jsx": "react", "strict": true, "forceConsistentCasingInFileNames": true, "noUnusedLocals": true, "esModuleInterop": true, "module": "ESNext", "target": "ESNext", "allowSyntheticDefaultImports": true, "moduleResolution": "node", "resolveJsonModule": true, "allowJs": true, "noEmit": true, "lib": ["ESNext", "DOM"], "baseUrl": "./src", "paths": {} }, "include": ["src/**/*",".vscode/babel.config.js"] }
babel.config.js
module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], ], };
package.json中的jest配置
"jest": { "transform": { "^.+\\.jsx?$": "babel-jest" }, "transformIgnorePatterns": [ "/node_modules/(?!(somePkg)|react-dnd|core-dnd|@react-dnd)" ] }
问题根源
出现这个错误的核心原因是:你的npm包没有被正确编译成Node.js/目标项目能识别的模块格式,或者目标项目没有正确处理node_modules里的这个包。
具体来说:
- npm包的
tsconfig设置了"noEmit": true,TypeScript不会输出编译后的JS文件,发布的可能只是源码,目标项目没对这个包做转译。 - 目标项目的jest配置里,
transformIgnorePatterns没把你的内部包加入白名单,Babel不会转译它,Node.js直接执行ES模块语法时报错。
解决步骤
1. 调整npm包的tsconfig配置
修改npm包的tsconfig.json,关闭noEmit并指定编译输出目录:
{ "compilerOptions": { // 保留原有其他配置 "noEmit": false, "outDir": "./dist" }, "include": ["src/**/*"] }
2. 配置npm包的package.json
在包的package.json里添加入口、类型定义和发布脚本,确保只发布编译后的文件:
{ "main": "./dist/index.js", "module": "./dist/index.mjs", // 可选,同时支持ES模块格式 "types": "./dist/index.d.ts", "files": ["dist"], "scripts": { "build": "tsc", "prepublishOnly": "npm run build" // 发布前自动编译 } }
3. 调整目标项目的jest配置
把你的内部npm包加入jest的转译白名单,让Babel处理它:
"jest": { "transform": { "^.+\\.jsx?$": "babel-jest" }, "transformIgnorePatterns": [ "/node_modules/(?!(somePkg)|react-dnd|core-dnd|@react-dnd|你的内部包名)" ] }
4. 验证模块格式兼容
- 如果目标项目
tsconfig是"module": "ESNext",确保npm包的tsconfig也设置了"module": "ESNext",或者用tsup/rollup同时输出ES和CommonJS两种格式。 - 如果npm包是ES模块,要在包的
package.json里加"type": "module",匹配Node.js 20的ES模块解析规则。
额外检查
- 本地运行
npm run build,确认dist目录生成了编译后的JS和类型文件。 - 发布后检查内部源里的包是否包含dist目录。
- 目标项目安装包后,查看
node_modules/你的包名下的文件结构是否正确。
内容的提问来源于stack exchange,提问作者marslfc
相关产品推荐
相关产品推荐

