TypeScript 中的 resolvePackageJsonExports
说明 resolvePackageJsonExports 为什么会让 TypeScript 读取 node_modules 包的 package.json exports 字段,以及它在 node16、nodenext、bundler 下默认就是开启的。
#tech / dev
#resource / typescript
#type / concept
#status / growing
[!info] related notes
TypeScript 中的 resolvePackageJsonExports
一句话定义
resolvePackageJsonExports 用来控制 TypeScript 在解析 node_modules 里的包时,是否读取 package.json 的 exports 字段。
核心机制 / 工作原理
官方文档直接说明:
- 它会强制 TypeScript 在读取
node_modules包时 consult the exports field
也就是说,TypeScript 解析:
import { foo } from "some-package";
时,不再只靠旧式入口文件习惯,还会把现代包导出条件纳入解析过程。
最小例子 / 最小场景
官方文档还明确给出一个关键默认值:
- 在
moduleResolution为node16、nodenext、bundler时,它默认就是true
所以现代项目里,很多人其实已经在用它,只是没有显式写出来。
边界与易混淆点
它不等于 customConditions
resolvePackageJsonExports决定要不要看exportscustomConditions决定看exports时还要不要额外加自定义条件名
它属于现代包解析模型的一部分
如果项目还停留在很旧的模块解析心智里,这个选项的存在感会不明显。
但对现代 Node / bundler 生态,它已经是主路径。
它通常和现代 moduleResolution 绑得很紧
最相关的仍然是:
参考信息
- TSConfig
resolvePackageJsonExports: https://www.typescriptlang.org/tsconfig/resolvePackageJsonExports.html