
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.json中module和moduleResolution设置为"node16"或"nodenext"。 - 确认项目
package.json中 不包含"type": "module",即项目为 CommonJS 模块。 - 运行
npx @arethetypeswrong/cli @langfuse/core可快速验证是否存在 CJS 解析失败问题。
解决步骤
- 等待
@langfuse/*包的维护者发布修复版本(已在 GitHub Issue 评论中确认将修复于 langfuse/langfuse-js#852)。 - 升级所有受影响的
@langfuse/*包至修复后的版本。 - 如果无法等待官方修复,可优先尝试以下临时方案:将 TypeScript 项目的
moduleResolution临时改为"bundler"或"classic",或者将项目本身改为 ESM 模块(在package.json中添加"type": "module")。 - 确保
npx tsc不再报错。
验证方法
在修复后,运行 npx tsc 应不再输出 TS1479 或 TS1541 错误。也可以执行 npx @arethetypeswrong/cli @langfuse/core 确认 CJS 解析失败问题已消失。



