从头开始创建最小 NestJS 应用程序的 5 个步骤!

2025-05-25

从头开始创建最小 NestJS 应用程序的 5 个步骤!

假设您想从头创建一个新的NestJS标准应用程序,但希望完全控制依赖项、脚本和源代码。因此,您不想使用通常的npx @nestjs/cli new命令(该命令基本上会引导TypeScript 启动项目),而希望创建一个最小应用程序。

本指南的目标是向您展示启动标准(基于 ExpressJS 的 HTTP 服务器) NestJS 应用程序真正需要什么。

这里使用的工具

  • Node.js v22——JavaScript 运行时(最低要求为 Node.js v20)
  • NPM——包管理器
  • npx——执行 NPM 包二进制文件的实用程序
  • bash shell——终端相关的东西。我们将在这里使用 UNIX 文档功能通过终端写入文件,但您也可以将其替换为您的 IDE,例如 VS Code。

当然,您可以使用它们的较新版本。

最终文件结构

结果如下:

.
├── nest-cli.json
├── package.json
├── package-lock.json
├── src
│   ├── app.module.ts
│   └── main.ts
├── tsconfig.build.json
└── tsconfig.json

1 directory, 7 files
Enter fullscreen mode Exit fullscreen mode
$ npm ls --depth=0
my-nestjs-app@1.0.0 /tmp/my-nestjs-app
├── @nestjs/cli@11.0.0
├── @nestjs/common@11.0.3
├── @nestjs/core@11.0.3
├── @nestjs/platform-express@11.0.3
├── @nestjs/schematics@11.0.0
├── @types/node@22.10.7
├── reflect-metadata@0.2.2
└── typescript@5.7.3
Enter fullscreen mode Exit fullscreen mode

包含 4 个开发依赖项和 4 个生产依赖项。并且仅需 3 个 NPM 脚本。

1. NPM项目设置

## Create the new directory that will holds our app's code
mkdir my-nestjs-app
## Enter on it
cd my-nestjs-app
## Start the NPM project
npm init --yes
Enter fullscreen mode Exit fullscreen mode

2. 安装所有必需的依赖项

作为硬性/生产依赖项,我们需要:

npm install reflect-metadata @nestjs/common @nestjs/core
##          |
##          +--> For TS decorators introspection

## Since we'll use express as the underlying HTTP lib:
npm install @nestjs/platform-express
Enter fullscreen mode Exit fullscreen mode

作为开发依赖项,我们得到:

npm install --save-dev typescript @types/node @nestjs/cli @nestjs/schematics
Enter fullscreen mode Exit fullscreen mode

您可以在此处了解有关 NPM 依赖项的更多信息。

3. 将有用的 npm-scripts 添加到 package.json

为了帮助构建和运行我们的应用程序,我们可以添加一些有用的npm-scripts

## Remove the 'test' npm-script that was generated by NPM before
npm pkg delete scripts.test
## Change the 'main' entry to the right entry file that we'll have after building the project
npm pkg set main="dist/src/main"

## Define the 'build' script,
## that will be used to compile our TypeScript code into JavaScript
npm pkg set scripts.build="nest build"

## Define the 'start:dev' script,
## that will be used to build & run the app with the watch mode
npm pkg set scripts.start:dev="nest start --watch"

## Define the 'start:prod' script,
## that will be used to run the compiled code 
npm pkg set scripts.start:prod="node ."
Enter fullscreen mode Exit fullscreen mode

看起来应该package.json是这样的:

{
  "name": "my-nestjs-app",
  "version": "1.0.0",
  "main": "dist/src/main",
  "scripts": {
    "build": "nest build",
    "start:dev": "nest start --watch",
    "start:prod": "node ."
  },
  "keywords": [],
  "author": "Micael Levi L. C.",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "@nestjs/common": "^11.0.3",
    "@nestjs/core": "^11.0.3",
    "@nestjs/platform-express": "^11.0.3",
    "reflect-metadata": "^0.2.2"
  },
  "devDependencies": {
    "@nestjs/cli": "^11.0.0",
    "@nestjs/schematics": "^11.0.0",
    "@types/node": "^22.10.7",
    "typescript": "^5.7.3"
  }
}
Enter fullscreen mode Exit fullscreen mode

4.创建所有必需的文件

  • 我们将创建一个src包含 NestJS 模块的目录,
  • tsconfig.json根目录中的文件
  • tsconfig.build.json根目录中用于编译生产环境的 TypeScript 项目的文件
  • 根目录中的一个nest-cli.json文件,用于配置 NestJS 的 CLI。

如果您不熟悉我们将在这些 TypeScript 配置文件中使用的配置选项(tsconfig ...),请查看其文档:https://www.typescriptlang.org/tsconfig

## Create the 'src' directory to store source files
mkdir src
Enter fullscreen mode Exit fullscreen mode
## Create the TypeScript configuration file with good defaults
cat <<EOF > tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2024",
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./",
    "baseUrl": "./",
    "skipLibCheck": true,
    "incremental": true
  }
}
EOF

## Create the TypeScript config file
## that will be used when building the project with NestJS's CLI
cat <<EOF > tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
EOF
Enter fullscreen mode Exit fullscreen mode
## Create the NestJS CLI config file
## Do note that we don't want to generate spec files while using the 'generate' command
## since we are not using Jest in this tutorial
## Also, Jest isn't mandatory.
## You could use any other testing framework that works with TS decorators
cat <<EOF > nest-cli.json
{
  "\$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "monorepo": false,
  "sourceRoot": "src",
  "entryFile": "main",
  "language": "ts",
  "generateOptions": {
    "spec": false
  },
  "compilerOptions": {
    "tsConfigPath": "./tsconfig.build.json",
    "webpack": false,
    "deleteOutDir": true,
    "assets": [],
    "watchAssets": false,
    "plugins": []
  }
}
EOF
Enter fullscreen mode Exit fullscreen mode
## Create a minimal application root module
npx nest generate module app --flat

## Create a minimal application entrypoint under src/main.ts file
cat <<EOF > src/main.ts
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  await app.listen(process.env.PORT || 3000);
}
bootstrap();
EOF
Enter fullscreen mode Exit fullscreen mode

5. 运行应用程序🎊

对于开发:

## For development
npm run start:dev
Enter fullscreen mode Exit fullscreen mode

对于生产:

## Setup for production
npm run build
## Delete the 'node_modules' directory
rm -rf node_modules
## Install production-only dependencies without changing the lock file
npm ci --omit=dev
## Start the app using it's 'main' entry
node .
Enter fullscreen mode Exit fullscreen mode

所有内容都在 bash 脚本中:https://github.com/micalevisk/create-nest/blob/main/create-nestjs-from-scratch.sh

文章来源:https://dev.to/micalevisk/5-steps-to-create-a-bare-minimum-nestjs-app-from-scratch-5c3b
PREV
我的 React.js 库书签荣誉提名 ➕
NEXT
如何在 Linux 更新 2024 上安装 Cursor AI 编辑器