NestJS安装与环境搭建 #

前置要求 #

在开始安装NestJS之前,请确保你的系统已安装以下软件:

Node.js #

NestJS需要Node.js(>= 16)运行环境。

检查Node.js版本:

bash
node -v

推荐使用LTS版本:

Node.js版本 状态 说明
20.x LTS 推荐 最新LTS版本
18.x LTS 推荐 稳定LTS版本
16.x 维护 最低支持版本

安装Node.js:

  • macOS/Linux:使用nvm(Node Version Manager)
  • Windows:使用nvm-windows或官方安装包
bash
# 使用nvm安装
nvm install 20
nvm use 20

npm/pnpm/yarn #

NestJS支持多种包管理器:

bash
# 检查npm版本
npm -v

# 检查yarn版本(如已安装)
yarn -v

# 检查pnpm版本(如已安装)
pnpm -v

安装Nest CLI #

Nest CLI是NestJS官方提供的命令行工具,用于快速创建项目、生成代码等。

全局安装 #

bash
# 使用npm
npm install -g @nestjs/cli

# 使用yarn
yarn global add @nestjs/cli

# 使用pnpm
pnpm add -g @nestjs/cli

验证安装 #

bash
nest -v
# 或
nest --version

CLI常用命令 #

命令 简写 说明
nest new n 创建新项目
nest generate g 生成文件
nest build b 构建项目
nest start s 启动项目
nest test t 运行测试
nest info i 显示项目信息

创建新项目 #

使用CLI创建 #

bash
nest new project-name

CLI会提示选择包管理器:

text
? Which package manager would you ❤️ to use?
  npm
  yarn
❯ pnpm

手动创建 #

如果需要更多控制,可以手动创建项目:

bash
# 创建项目目录
mkdir my-nest-project
cd my-nest-project

# 初始化package.json
npm init -y

# 安装核心依赖
npm install @nestjs/core @nestjs/common @nestjs/platform-express rxjs reflect-metadata

# 安装开发依赖
npm install -D typescript @types/node @types/express ts-node nodemon

项目启动 #

开发模式 #

bash
# 启动开发服务器
npm run start:dev

开发模式支持热重载,修改代码后自动重启。

生产模式 #

bash
# 构建项目
npm run build

# 启动生产服务器
npm run start:prod

访问应用 #

默认情况下,NestJS应用运行在 http://localhost:3000

bash
# 使用curl测试
curl http://localhost:3000

# 响应
Hello World!

开发工具推荐 #

VS Code扩展 #

推荐安装以下VS Code扩展:

扩展名 说明
NestJS Files 快速创建NestJS文件
TypeScript Hero TypeScript代码导航
ESLint 代码检查
Prettier 代码格式化
REST Client API测试

推荐的VS Code配置 #

在项目根目录创建 .vscode/settings.json

json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "typescript.tsdk": "node_modules/typescript/lib"
}

推荐的VS Code启动配置 #

创建 .vscode/launch.json

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug NestJS",
      "runtimeExecutable": "npm",
      "runtimeArgs": ["run", "start:debug"],
      "console": "integratedTerminal"
    }
  ]
}

项目脚本说明 #

package.json 中预定义的脚本:

json
{
  "scripts": {
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "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:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  }
}
脚本 说明
npm run build 构建生产代码
npm run start 启动应用
npm run start:dev 开发模式(热重载)
npm run start:debug 调试模式
npm run test 运行单元测试
npm run test:e2e 运行E2E测试
npm run lint 代码检查

环境变量配置 #

安装配置模块 #

bash
npm install @nestjs/config

创建环境文件 #

创建 .env 文件:

env
PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/mydb

配置ConfigModule #

typescript
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}

使用环境变量 #

typescript
constructor(private configService: ConfigService) {}

const dbUrl = this.configService.get<string>('DATABASE_URL');

常见问题 #

1. 端口被占用 #

bash
# 查找占用端口的进程
lsof -i :3000

# 终止进程
kill -9 <PID>

2. 权限问题 #

在macOS/Linux上,可能需要修复npm权限:

bash
# 使用nvm可以避免权限问题
# 或修改npm默认目录
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

3. 网络问题 #

如果npm安装缓慢,可以使用国内镜像:

bash
# 使用淘宝镜像
npm config set registry https://registry.npmmirror.com

# 或使用cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com

总结 #

本章介绍了NestJS开发环境的搭建过程,包括:

  • Node.js和npm的安装
  • Nest CLI的安装和使用
  • 项目的创建和启动
  • 开发工具的配置

接下来,让我们创建 第一个NestJS应用

最后更新:2026-03-28