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

如何配置Monorepo的tsconfig.json,让每个工作区生成dist文件夹

Monorepo TypeScript配置调整:将.d.ts生成到子包dist目录

当前问题:执行tsc时,.d.ts文件生成在子包的src目录中,且src下文件被干扰,期望将编译产物(含.d.ts)输出到每个子包根目录的dist文件夹。

需要修改以下配置:

1. 根目录tsconfig.json调整

  • 在compilerOptions中添加composite: true(启用Project References的必要配置)
  • 添加references字段,指定所有子包路径,让根目录编译时识别子包配置
  • 更新exclude字段,排除子包的dist目录,避免重复处理已生成文件
  • 可选:将根目录的declaration设为false,由子包单独控制声明文件生成

修改后的根目录tsconfig.json示例:

{
  "exclude": [
    "node_modules/*",
    "example/*",
    "packages/*/dist"
  ],
  "references": [
    { "path": "./packages/packages-A" },
    { "path": "./packages/packages-B" }
  ],
  "compilerOptions": {
    "allowJs": true,
    "module": "es6",
    "declaration": false,
    "skipLibCheck": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "jsx": "react",
    "lib": [
      "esnext"
    ],
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "strict": true,
    "target": "esnext",
    "composite": true
  }
}

2. 子包tsconfig.json调整

  • 在compilerOptions中添加composite: true,配合根目录的Project References使用
  • 显式指定declarationDir: "./dist"(确保声明文件输出到dist目录,与outDir保持一致)
  • 确保include仅包含src/**/*,避免编译范围错误
  • 开启declaration: true,明确子包生成声明文件

修改后的子包tsconfig.json示例:

{
  "extends": "../../tsconfig.json",
  "include": [
    "src/**/*"
  ],
  "compilerOptions": {
    "outDir": "./dist",
    "declarationDir": "./dist",
    "composite": true,
    "declaration": true
  }
}

3. 编译命令调整

不再直接执行tsc,而是在根目录执行:

tsc --build
# 或简写
tsc -b

该命令会按照Project References的规则,单独处理每个子包的配置,将所有编译产物(.js、.d.ts等)输出到对应子包的dist目录中。

可选:子包package.json配置

为了让其他包正确引用,可在子包的package.json中添加入口指向:

{
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:43:10