NestJS项目结构解析 #
默认项目结构 #
使用Nest CLI创建的项目结构如下:
text
hello-nest/
├── node_modules/ # 依赖包
├── src/ # 源代码目录
│ ├── app.controller.spec.ts # 控制器单元测试
│ ├── app.controller.ts # 根控制器
│ ├── app.module.ts # 根模块
│ ├── app.service.ts # 根服务
│ └── main.ts # 应用入口
├── test/ # E2E测试目录
│ ├── app.e2e-spec.ts # E2E测试文件
│ └── jest-e2e.json # Jest E2E配置
├── .eslintrc.js # ESLint配置
├── .gitignore # Git忽略文件
├── .prettierrc # Prettier配置
├── nest-cli.json # Nest CLI配置
├── package.json # 项目配置
├── tsconfig.build.json # TypeScript构建配置
└── tsconfig.json # TypeScript配置
核心文件详解 #
main.ts - 应用入口 #
typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
职责:
- 创建Nest应用实例
- 配置全局中间件
- 启动HTTP服务器
app.module.ts - 根模块 #
typescript
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
职责:
- 作为应用的根模块
- 组织和导入其他模块
- 注册全局提供者
app.controller.ts - 根控制器 #
typescript
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
职责:
- 处理根路由请求
- 定义API端点
app.service.ts - 根服务 #
typescript
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
职责:
- 包含业务逻辑
- 被控制器调用
- 可被注入到其他类中
推荐的项目结构 #
对于中大型项目,推荐以下结构:
text
src/
├── main.ts # 应用入口
├── app.module.ts # 根模块
│
├── common/ # 公共模块
│ ├── decorators/ # 自定义装饰器
│ │ └── current-user.decorator.ts
│ ├── filters/ # 异常过滤器
│ │ └── http-exception.filter.ts
│ ├── guards/ # 守卫
│ │ └── jwt-auth.guard.ts
│ ├── interceptors/ # 拦截器
│ │ └── logging.interceptor.ts
│ ├── interfaces/ # 公共接口
│ │ └── response.interface.ts
│ ├── middleware/ # 中间件
│ │ └── logger.middleware.ts
│ ├── pipes/ # 管道
│ │ └── validation.pipe.ts
│ └── common.module.ts # 公共模块
│
├── config/ # 配置文件
│ ├── database.config.ts
│ ├── jwt.config.ts
│ └── configuration.ts
│
├── modules/ # 功能模块
│ ├── auth/ # 认证模块
│ │ ├── auth.controller.ts
│ │ ├── auth.module.ts
│ │ ├── auth.service.ts
│ │ ├── dto/
│ │ │ ├── login.dto.ts
│ │ │ └── register.dto.ts
│ │ ├── strategies/
│ │ │ └── jwt.strategy.ts
│ │ └── interfaces/
│ │ └── jwt-payload.interface.ts
│ │
│ ├── users/ # 用户模块
│ │ ├── users.controller.ts
│ │ ├── users.module.ts
│ │ ├── users.service.ts
│ │ ├── entities/
│ │ │ └── user.entity.ts
│ │ ├── dto/
│ │ │ ├── create-user.dto.ts
│ │ │ └── update-user.dto.ts
│ │ └── interfaces/
│ │ └── user.interface.ts
│ │
│ └── products/ # 产品模块
│ ├── products.controller.ts
│ ├── products.module.ts
│ ├── products.service.ts
│ └── ...
│
├── entities/ # 全局实体
│ └── base.entity.ts
│
└── database/ # 数据库配置
├── migrations/ # 迁移文件
└── seeds/ # 种子数据
模块目录结构 #
每个功能模块推荐的结构:
text
users/
├── users.module.ts # 模块定义
├── users.controller.ts # 控制器
├── users.controller.spec.ts # 控制器测试
├── users.service.ts # 服务
├── users.service.spec.ts # 服务测试
├── entities/ # 数据实体
│ └── user.entity.ts
├── dto/ # 数据传输对象
│ ├── create-user.dto.ts
│ └── update-user.dto.ts
├── interfaces/ # 接口定义
│ └── user.interface.ts
├── schemas/ # MongoDB Schema
│ └── user.schema.ts
├── repositories/ # 仓库层
│ └── users.repository.ts
├── constants/ # 常量
│ └── users.constants.ts
└── utils/ # 工具函数
└── users.utils.ts
配置文件说明 #
nest-cli.json #
Nest CLI配置文件:
json
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
| 配置项 | 说明 |
|---|---|
collection |
使用的schematics集合 |
sourceRoot |
源代码目录 |
compilerOptions |
编译选项 |
tsconfig.json #
TypeScript配置:
json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": true,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true
}
}
package.json #
项目配置和依赖:
json
{
"name": "hello-nest",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:e2e": "jest --config ./test/jest-e2e.json"
}
}
命名规范 #
文件命名 #
| 类型 | 命名规范 | 示例 |
|---|---|---|
| 模块 | *.module.ts |
users.module.ts |
| 控制器 | *.controller.ts |
users.controller.ts |
| 服务 | *.service.ts |
users.service.ts |
| DTO | *.dto.ts |
create-user.dto.ts |
| 接口 | *.interface.ts |
user.interface.ts |
| 实体 | *.entity.ts |
user.entity.ts |
| 守卫 | *.guard.ts |
jwt-auth.guard.ts |
| 中间件 | *.middleware.ts |
logger.middleware.ts |
| 管道 | *.pipe.ts |
validation.pipe.ts |
| 拦截器 | *.interceptor.ts |
logging.interceptor.ts |
| 过滤器 | *.filter.ts |
http-exception.filter.ts |
类命名 #
| 类型 | 命名规范 | 示例 |
|---|---|---|
| 模块 | PascalCase + Module | UsersModule |
| 控制器 | PascalCase + Controller | UsersController |
| 服务 | PascalCase + Service | UsersService |
| DTO | PascalCase + DTO | CreateUserDto |
| 接口 | PascalCase | User |
| 实体 | PascalCase | User |
| 守卫 | PascalCase + Guard | JwtAuthGuard |
使用CLI生成代码 #
Nest CLI可以快速生成各种文件:
bash
# 生成模块
nest g module users
# 生成控制器
nest g controller users
# 生成服务
nest g service users
# 同时生成模块、控制器、服务
nest g resource users
# 生成守卫
nest g guard auth/jwt
# 生成拦截器
nest g interceptor logging
# 生成过滤器
nest g filter http-exception
# 生成管道
nest g pipe validation
# 生成装饰器
nest g decorator current-user
# 生成中间件
nest g middleware logger
CLI选项 #
| 选项 | 说明 |
|---|---|
--no-spec |
不生成测试文件 |
--flat |
不创建文件夹 |
--module <module> |
指定注册的模块 |
bash
# 不生成测试文件
nest g service users --no-spec
# 注册到指定模块
nest g controller users --module app
最佳实践 #
1. 模块划分原则 #
- 按业务功能划分模块
- 每个模块职责单一
- 高内聚、低耦合
2. 目录组织 #
- 相关文件放在同一目录
- 使用index.ts导出公共接口
- 避免过深的目录嵌套
3. 代码分层 #
text
Controller → Service → Repository → Database
↓ ↓
DTO Entity
4. 模块导入导出 #
typescript
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // 导出供其他模块使用
})
export class UsersModule {}
总结 #
本章详细解析了NestJS项目结构:
- 默认项目结构和文件职责
- 推荐的中大型项目结构
- 配置文件说明
- 命名规范
- CLI代码生成
接下来,让我们深入学习 模块(Module)。
最后更新:2026-03-28