bug: CJS type mismatch when using @langfuse/langchain with TypeScript nodenext module resolution

用户在使用 TypeScript 并将 moduleResolution 设置为 "node16" 或 "nodenext" 时,导入 @langfuse/core 、 @langfuse/client 、 @langfuse/tracing 、 @langfuse/otel 、 @langfuse

bug: CJS type mismatch when using @langfuse/langchain with TypeScript nodenext module resolution

bug: CJS type mismatch when using @langfuse/langchain with TypeScript nodenext module resolution

快速结论:该报错发生在 TypeScript 项目使用 moduleResolution: "node16""nodenext" 模式时,且项目本身是 CommonJS 模块。优先检查 @langfuse/* 包的 exports 映射是否按 TypeScript 4.7 规范为 import/require 分支分别配置了 "types" 条件。

问题场景

用户在使用 TypeScript 并将 moduleResolution 设置为 "node16""nodenext" 时,导入 @langfuse/core@langfuse/client@langfuse/tracing@langfuse/otel@langfuse/openai@langfuse/langchain@langfuse/browser@langfuse/* 包时触发类型解析失败。项目本身为 CommonJS 模块(package.json 中不包含 "type": "module"),使用 npx tsc 进行类型检查时遇到错误。

报错原文

TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'.

TS1541: Cannot import type from an ECMAScript module in a CommonJS module.

原因分析

可能原因:@langfuse/*package.json 中声明了 "type": "module"(即包本身是 ESM),且 exports 映射仅暴露了单一的顶级 "types": "./dist/index.d.ts"。TypeScript 4.7 规范要求:在 node16/nodenext 模块解析模式下,包的 exports 映射应在每个 import/require 分支下嵌套 "types" 条件,以便 CommonJS 消费者解析 .d.cts 声明文件、ESM 消费者解析 .d.ts。当前 tsup 构建工具虽然生成了对应的 .d.cts 声明文件,但该文件未被 exports 映射引用,导致 CommonJS 消费者无法使用。

环境排查

  • 确认 TypeScript 版本不低于 4.7(moduleResolution: "node16" 需要此版本)。
  • 确认 tsconfig.jsonmodulemoduleResolution 设置为 "node16""nodenext"
  • 确认项目 package.json不包含 "type": "module",即项目为 CommonJS 模块。
  • 运行 npx @arethetypeswrong/cli @langfuse/core 可快速验证是否存在 CJS 解析失败问题。

解决步骤

  1. 等待 @langfuse/* 包的维护者发布修复版本(已在 GitHub Issue 评论中确认将修复于 langfuse/langfuse-js#852)。
  2. 升级所有受影响的 @langfuse/* 包至修复后的版本。
  3. 如果无法等待官方修复,可优先尝试以下临时方案:将 TypeScript 项目的 moduleResolution 临时改为 "bundler""classic",或者将项目本身改为 ESM 模块(在 package.json 中添加 "type": "module")。
  4. 确保 npx tsc 不再报错。

验证方法

在修复后,运行 npx tsc 应不再输出 TS1479 或 TS1541 错误。也可以执行 npx @arethetypeswrong/cli @langfuse/core 确认 CJS 解析失败问题已消失。

参考来源

langfuse/langfuse #14640

GamsGo AI

AI 工具推荐

想把多个 AI 模型放在一个入口?

GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。

了解 GamsGo AI

推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。

celebrityanime
celebrityanime
文章: 10632

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注