记录本人实际项目开发的需求,将公共类型、业务模块类型、通用响应结构等,抽离为一个独立的包 @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 和验证 |
918

被折叠的 条评论
为什么被折叠?



