You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yarn 4 Monorepo中TypeScript桶文件隐式导入配置问题

解决Yarn 4 + TypeScript Monorepo中桶文件隐式导入问题

要同时兼容单文件直接导入和目录桶文件的隐式导入,只需调整@example/common包的package.json中的exports字段,按以下方式配置:

修改@example/common的package.json

更新exports映射,优先匹配目录的桶文件,再回退到单文件:

{
  "name": "@example/common",
  "exports": {
    "./*": [
      "./lib/*/index.js",
      "./lib/*/index.d.ts",
      "./lib/*.js",
      "./lib/*.d.ts"
    ]
  },
  // 其他配置...
}

配置说明

  • Node.js(以及启用node16模块解析的TypeScript)会按exports数组的顺序匹配路径:
    1. 当导入@example/common/utils时,首先检查是否存在lib/utils/index.js和对应的类型文件,存在则加载桶文件
    2. 如果不存在该目录结构(即对应单文件lib/utils.js),则匹配后面的单文件规则,保留原有导入逻辑
  • 无需修改TypeScript的paths配置,node16模式会直接遵循package.json的exports规则,类型校验和运行时均可正常工作

验证要点

  • 确保@example/common构建后,lib目录同时包含:
    • 单文件产物(如utils.js对应src/utils.ts)
    • 目录结构产物(如utils/index.js、utils/stuff.js对应src/utils目录)
  • 在子项目中测试两种导入场景:
    • import { ... } from '@example/common/utils' → 自动加载目录桶文件
    • import { ... } from '@example/common/other' → 正常加载单文件

内容的提问来源于stack exchange,提问作者Martin Wedvich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:32:18