Skip to content
第 166 / 250 章Node⏱ 12 分钟阅读

第 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。

维度TypeORMPrisma
学习曲线⭐⭐ 平缓⭐⭐⭐ 中等
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

维度ExpressKoaNestJS
学习曲线⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
架构自由极简模块化
适用小工具中间件企业应用
TS 支持原生
DI内置
生态最大增长快

五、NestJS 适用场景

六、什么时候不用 NestJS

  • 极致轻量:用 Fastify 裸跑
  • 超小项目:Vite + Express 即可
  • 前端 SSR:用 Next.js / Nuxt
  • Python/Go 项目:用对应语言框架

七、本章小结

概念关键
NestJS渐进式 Node.js 框架
设计哲学借鉴 Angular + Spring
核心模块化 + DI + AOP
ORMTypeORM(本章选用)
适合企业级 API / 微服务

动手练习

  1. 打开 https://nestjs.com 阅读 "Introduction"
  2. 对比 SpringBoot @Controller 和 NestJS @Controller
  3. 想一想你之前用 SpringBoot 写的项目,NestJS 会怎么写?

推荐阅读


下一章:第 167 章:环境搭建

本站基于 VitePress 构建 · 由 Codebook 团队维护