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

如何在Monorepo公开仓库打包中包含私有仓库的类型定义?

解决Yarn PnP Monorepo中私有类型仓库与公开库一同发布的问题

你的问题核心是:Monorepo内的私有@types工作区包,在公开库my-public-library中通过export * from "@types"导出后,打包产物未包含这些类型,导致发布后用户无法获取。这是因为打包工具默认不会将工作区依赖的类型/代码合并到产物中,需要针对性调整配置。

以下是具体解决步骤:

  • 配置TypeScript生成完整类型声明
    在my-public-library的tsconfig.json中,开启类型声明生成,并通过paths正确指向私有@types的源码路径:

    {
      "compilerOptions": {
        "declaration": true, // 生成.d.ts类型声明文件
        "declarationMap": true, // 生成类型映射文件(可选,便于调试)
        "baseUrl": ".",
        "paths": {
          "@types": ["../@types/src"] // 根据你的Monorepo目录结构调整路径
        }
      }
    }
    
  • 修改打包工具配置,强制打包私有类型依赖
    不同打包工具的配置方式略有差异,这里给出两种常用工具的配置示例:

    • tsup:在tsup.config.ts中启用dts生成,并设置bundle: true确保工作区依赖被打包进产物:
      import { defineConfig } from "tsup";
      
      export default defineConfig({
        entry: ["index.ts"],
        dts: true, // 自动生成并合并类型声明
        sourcemap: true,
        clean: true,
        bundle: true, // 强制打包所有依赖(包括私有@types)
      });
      
    • Rollup:安装@rollup/plugin-typescript后,配置TypeScript插件生成类型声明,并避免将@types标记为外部依赖:
      import typescript from "@rollup/plugin-typescript";
      
      export default {
        input: "index.ts",
        output: [
          { file: "dist/index.js", format: "esm" },
          { file: "dist/index.cjs", format: "cjs" }
        ],
        plugins: [
          typescript({
            declaration: true,
            declarationDir: "dist",
            tsconfig: "./tsconfig.json"
          })
        ],
        external: [] // 不要将@types加入外部依赖列表
      };
      
  • 配置package.json指向类型产物
    在my-public-library的package.json中,指定types字段指向打包后生成的类型文件,确保用户能正确识别类型:

    {
      "types": "./dist/index.d.ts",
      // 若打包时已将@types合并进产物,可移除@types的workspace依赖,避免用户安装时出现私有包无法获取的问题
      "dependencies": {
        // "@types": "workspace:*" 可删除
      }
    }
    
  • 验证打包结果
    执行打包命令后,打开dist/index.d.ts文件,确认其中包含@types导出的所有类型定义,比如:

    export enum BUTTON_TAG {
      BUTTON = "button",
      ANCHOR = "a",
    }
    export type ButtonTag = `${BUTTON_TAG}`;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:25:09