Skip to content

代码生成器

youlai-nest 提供代码生成工具,快速生成 CRUD 代码。

使用方式

1. 运行生成器

bash
# 交互式生成
pnpm run gen

# 指定表名生成
pnpm run gen:user --table=sys_user

2. 配置模板

配置文件 codegen/config.yaml

yaml
# 数据库连接
database:
  host: localhost
  port: 3306
  username: root
  password: 123456
  database: youlai_admin

# 生成配置
output:
  baseDir: src/modules
  override: false # 是否覆盖已有文件

# 模板配置
template:
  entity: templates/entity.ts.hbs
  service: templates/service.ts.hbs
  controller: templates/controller.ts.hbs
  dto: templates/dto.ts.hbs

3. 生成的文件结构

src/modules/user/
├── user.entity.ts       # 实体类
├── user.service.ts      # 服务层
├── user.controller.ts   # 控制器
├── user.dto.ts          # DTO 定义
└── user.module.ts       # 模块注册

生成的实体示例

typescript
@Entity("sys_user")
export class User {
  @PrimaryGeneratedColumn({ type: "bigint" }) id: number;
  @Column({ length: 50 }) username: string;
  @Column() deptId: number;
}

自定义模板

模板使用 Handlebars 语法,位于 templates/ 目录,可按需修改。

字段类型映射

MySQL 类型TypeScript 类型
bigintnumber
varcharstring
textstring
datetimeDate
tinyintnumber
decimalnumber
jsonobject

注意事项

  1. 生成后需手动检查字段类型和关联关系
  2. 权限控制需手动添加
  3. 复杂业务逻辑需手动实现

基于 MIT 许可发布 · 由 ❤️ 和 ☕ 驱动 · 支持作者