pnpm monorepo中Nest.js微服务引入types包报Unexpected token 'export'错误
解决Nest.js微服务中使用Monorepo类型包时的SyntaxError: Unexpected token 'export'错误
问题原因
你遇到的错误是因为Node.js运行时无法直接解析TypeScript的export语法——当前你的@aquaexplore/types包直接将TS源文件设为入口(main和types字段指向index.ts),且未完成编译构建,导致服务引用时尝试执行原始TS代码,触发语法错误。
解决方案
1. 配置TypeScript编译输出
在@aquaexplore/types包根目录创建tsconfig.json,指定编译输出目录和规则:
{ "compilerOptions": { "target": "ES2021", "module": "CommonJS", // 若主应用用ESM则改为ESNext "declaration": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["index.ts", "dtos/**/*", "entities/**/*"], "exclude": ["node_modules", "dist"] }
2. 更新package.json配置
修改@aquaexplore/types的package.json,将入口指向编译后的JS和类型文件:
{ "name": "@aquaexplore/types", "version": "1.0.0", "description": "", "type": "module", // 主应用是CommonJS则移除该行或改为"commonjs" "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc --build" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@nestjs/swagger": "^7.3.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "zod": "^3.22.4" } }
3. 构建类型包
在@aquaexplore/types包目录执行构建命令:
pnpm build
4. 同步主应用依赖
回到Monorepo根目录更新依赖:
pnpm install
额外注意事项
- 若主应用使用CommonJS模块格式,需保证
@aquaexplore/types的模块格式与其一致,避免跨模块类型解析冲突。 - 主应用的
tsconfig.json中,建议将compilerOptions.moduleResolution设为NodeNext或Node16,确保正确识别Monorepo包的类型定义。
内容的提问来源于stack exchange,提问作者eliotfgn
相关产品推荐
相关产品推荐

