第 166 章:为什么选 NestJS + TypeORM
学习目标
- 了解 NestJS 的定位与设计哲学
- 理解为什么选 TypeORM
- 对比 Express / Koa / NestJS
- 在新项目中正确选择 NestJS 生态
一、NestJS 是什么
NestJS 是一个用于构建服务端应用的渐进式 Node.js 框架,完全支持 TypeScript,设计哲学深受 Angular 影响。
二、为什么选 NestJS
2.1 对 Java 开发者最友好
你学过 SpringBoot,NestJS 的设计几乎一一对应:
2.2 三大核心特性
2.3 一段代码感受一下
typescript
// app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
// ① 构造器注入(类似 Spring 的 @Autowired)
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}typescript
// app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable() // ② 类似 Spring 的 @Service
export class AppService {
getHello(): string {
return 'Hello NestJS!';
}
}typescript
// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [], // ③ 引入其他模块
controllers: [AppController], // ④ 注册控制器
providers: [AppService], // ⑤ 注册服务
})
export class AppModule {}三、为什么选 TypeORM
NestJS 官方文档默认 TypeORM 集成,装饰器风格最像 Java 的 JPA/Hibernate。
| 维度 | TypeORM | Prisma |
|---|---|---|
| 学习曲线 | ⭐⭐ 平缓 | ⭐⭐⭐ 中等 |
| Java 熟悉度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 类型安全 | 中 | 极强 |
| 文档质量 | 中 | 极佳 |
| 性能 | 中 | 中 |
typescript
// entity/user.entity.ts - 像 JPA 一样自然
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({ unique: true })
email: string;
@OneToMany(() => Post, post => post.user)
posts: Post[];
@CreateDateColumn()
createdAt: Date;
}四、NestJS vs Express vs Koa
| 维度 | Express | Koa | NestJS |
|---|---|---|---|
| 学习曲线 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| 架构 | 自由 | 极简 | 模块化 |
| 适用 | 小工具 | 中间件 | 企业应用 |
| TS 支持 | 弱 | 弱 | 原生 |
| DI | 无 | 无 | 内置 |
| 生态 | 最大 | 中 | 增长快 |
五、NestJS 适用场景
六、什么时候不用 NestJS
- 极致轻量:用 Fastify 裸跑
- 超小项目:Vite + Express 即可
- 前端 SSR:用 Next.js / Nuxt
- Python/Go 项目:用对应语言框架
七、本章小结
| 概念 | 关键 |
|---|---|
| NestJS | 渐进式 Node.js 框架 |
| 设计哲学 | 借鉴 Angular + Spring |
| 核心 | 模块化 + DI + AOP |
| ORM | TypeORM(本章选用) |
| 适合 | 企业级 API / 微服务 |
动手练习
- 打开 https://nestjs.com 阅读 "Introduction"
- 对比 SpringBoot @Controller 和 NestJS @Controller
- 想一想你之前用 SpringBoot 写的项目,NestJS 会怎么写?
推荐阅读
下一章:第 167 章:环境搭建 →