Monorepo 项目类型设计方案

记录本人实际项目开发的需求,将公共类型、业务模块类型、通用响应结构等,抽离为一个独立的包 @your-org/types。这样可以被多个 app 或包直接复用。


📁 目录结构设计(推荐方案)

your-monorepo/
├── apps/
│   ├── admin/               # 管理后台
│   ├── shop/                # 商城前台
│   └── api/                 # API 服务端
├── packages/
│   ├── ui/                  # 公共 UI 组件
│   ├── types/               # ✅ 所有项目共享类型库
│   │   ├── src/
│   │   │   ├── shared/      # 通用类型(分页、响应体、枚举等)
│   │   │   └── modules/     # 业务模块类型
│   │   │       ├── product/
│   │   │       ├── user/
│   │   │       ├── order/
│   │   │       └── ...
│   │   └── index.ts         # 导出所有类型
│   └── ...
├── tsconfig.base.json       # tsconfig 基础配置
└── ...

📦 packages/types/src/ 结构示例

shared/(通用类型)

// shared/common.ts
export type OptionType = { label: string; value: string | number };
export type StatusType = "enabled" | "disabled" | "deleted";

// shared/pagination.ts
export interface PageRequest {
  page: number;
  pageSize: number;
}
export interface PageResponse<T> {
  total: number;
  list: T[];
}

// shared/response.ts
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

modules/product/types.ts

export interface Product {
  id: string;
  name: string;
  price: number;
  stock: number;
  status: StatusType;
  categoryId: string;
  imageUrl: string;
  createdAt: string;
}

export interface ProductFormValues {
  name: string;
  price: number;
  stock: number;
  categoryId: string;
  imageUrl: string;
}

export interface ProductTableItem extends Product {
  categoryName: string;
}

modules/user/types.ts

export interface User {
  id: string;
  username: string;
  email: string;
  role: "admin" | "customer";
  status: StatusType;
  createdAt: string;
}

📥 index.ts 导出统一管理

// packages/types/src/index.ts
export * from "./shared/common";
export * from "./shared/response";
export * from "./shared/pagination";

export * from "./modules/product/types";
export * from "./modules/user/types";
export * from "./modules/order/types";

🛠 在其他项目中使用

apps/admin/tsconfig.json

确保引入路径别名(配合 Turborepo 已配置的路径):

{
  "compilerOptions": {
    "paths": {
      "@your-org/types": ["../../packages/types/src"]
    }
  }
}

使用示例:

import type { Product, PageResponse } from "@your-org/types";

✅ 优势总结

优势描述
📦 模块解耦每个模块的类型独立,便于维护
🔄 高复用共用类型统一维护,不重复定义
🌍 多端共享后台、前台、服务端均可使用
🧪 更好测试类型更清晰,更容易 mock 和验证
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值