NestJS 开源项目教程
1. 项目的目录结构及介绍
NestJS 项目的目录结构通常如下:
nest-project/
├── src/
│ ├── app.module.ts
│ ├── main.ts
│ ├── controllers/
│ ├── services/
│ ├── entities/
│ └── ...
├── test/
├── node_modules/
├── package.json
├── tsconfig.json
└── nest-cli.json
目录结构介绍
- src/: 包含项目的源代码。
- app.module.ts: 应用程序的根模块。
- main.ts: 应用程序的入口文件。
- controllers/: 包含控制器文件,负责处理传入的请求和返回响应。
- services/: 包含服务文件,负责业务逻辑。
- entities/: 包含实体文件,通常用于数据库模型。
- ...: 其他可能的目录和文件,如中间件、过滤器等。
- test/: 包含测试文件。
- node_modules/: 包含项目依赖的模块。
- package.json: 项目的配置文件,包含依赖、脚本等信息。
- tsconfig.json: TypeScript 的配置文件。
- nest-cli.json: NestJS CLI 的配置文件。
2. 项目的启动文件介绍
main.ts
main.ts
是 NestJS 应用程序的入口文件,负责启动应用程序。以下是一个典型的 main.ts
文件内容:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
启动文件介绍
- NestFactory.create(AppModule): 创建一个 Nest 应用程序实例,传入根模块
AppModule
。 - app.listen(3000): 启动应用程序,监听端口 3000。
3. 项目的配置文件介绍
package.json
package.json
文件包含了项目的元数据和依赖信息。以下是一个典型的 package.json
文件内容:
{
"name": "nest-project",
"version": "0.0.1",
"description": "",
"author": "",
"license": "MIT",
"scripts": {
"start": "nest start",
"build": "nest build",
"test": "jest"
},
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/platform-express": "^8.0.0",
"reflect-metadata": "^0.1.13",
"typescript": "^4.3.5"
},
"devDependencies": {
"@nestjs/testing": "^8.0.0",
"jest": "^27.0.6"
}
}
配置文件介绍
- scripts: 定义了项目的脚本命令,如
start
、build
和test
。 - dependencies: 项目的运行时依赖。
- devDependencies: 项目的开发依赖。
tsconfig.json
tsconfig.json
文件是 TypeScript 的配置文件,定义了编译选项。以下是一个典型的 tsconfig.json
文件内容:
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
}
}
配置文件介绍
- compilerOptions: 定义了 TypeScript 编译器的选项。
- module: 指定模块系统。
- target: 指定编译目标。
- outDir: 指定输出