Nest探索(三)@nest/cli 学习

162 阅读3分钟

写原创好文,瓜分万元现金大奖 💰 |3月金石计划

前言

Nest 开源项目近年来用于服务端的开发很火爆,支持 TS、可以快速、高效地开发一个server端项目。而 Nest 借助 @nestjs/cli 提供了工程化的能力,比如创建项目、开发构建、编译项目等,@nestjs/cli 包目前也有了1.9k star。

Nest探索(一)Nest项目入门 中,我们全局安装了 @nestjs/cli,然后再执行命令nest new nestjs-demo-240127创建一个新项目。当然,我们也能通过npx @nestjs/cli new 项目名创建项目,这样每次临时获取的都是最新的npm包。

这里,我们将探索 @nestjs/cli 包的常用命令。

nest -h

首先看下 nest 包含了哪些命令:

$ nest -h
Usage: nest <command> [options]Options:
  -v, --version                                   Output the current version.
  -h, --help                                      Output usage information.  
​
Commands:
  new|n [options] [name]                          Generate Nest application. 
  build [options] [app]                           Build Nest application.    
  start [options] [app]                           Run Nest application.      
  info|i                                          Display Nest project details.      
  add [options] <library>                         Adds support for an external library to your project.
  generate|g [options] <schematic> [name] [path]  Generate a Nest element.
    Schematics available on @nestjs/schematics collection:
      ┌───────────────┬─────────────┬──────────────────────────────────────────────┐ 
      │ name          │ alias       │ description                                  │ 
      │ application   │ applicationGenerate a new application workspace         │ 
      │ class         │ cl          │ Generate a new class                         │ 
      │ configurationconfig      │ Generate a CLI configuration file            │ 
      │ controller    │ co          │ Generate a controller declaration            │ 
      │ decorator     │ d           │ Generate a custom decorator                  │ 
      │ filter        │ f           │ Generate a filter declaration                │ 
      │ gateway       │ ga          │ Generate a gateway declaration               │ 
      │ guard         │ gu          │ Generate a guard declaration                 │ 
      │ interceptor   │ itc         │ Generate an interceptor declaration          │ 
      │ interface     │ itf         │ Generate an interface                        │ 
      │ library       │ lib         │ Generate a new library within a monorepo     │ 
      │ middleware    │ mi          │ Generate a middleware declaration            │ 
      │ module        │ mo          │ Generate a module declaration                │ 
      │ pipe          │ pi          │ Generate a pipe declaration                  │ 
      │ provider      │ pr          │ Generate a provider declaration              │ 
      │ resolver      │ r           │ Generate a GraphQL resolver declaration      │ 
      │ resource      │ res         │ Generate a new CRUD resource                 │ 
      │ service       │ s           │ Generate a service declaration               │ 
      │ sub-app       │ app         │ Generate a new application within a monorepo │ 
      └───────────────┴─────────────┴──────────────────────────────────────────────┘ 

nest new

nest new 用于创建一个新的 nest 项目。有以下选项:

$ nest new -h
Usage: nest new|n [options] [name]
​
Generate Nest application.
​
Options:
  --directory [directory]                 Specify the destination directory
  -d, --dry-run                           Report actions that would be performed without writing out results. (default: false)
  -g, --skip-git                          Skip git repository initialization. (default: false)
  -s, --skip-install                      Skip package installation. (default: false)
  -p, --package-manager [packageManager]  Specify package manager.
  -l, --language [language]               Programming language to be used (TypeScript or JavaScript) (default: "TypeScript")  
  -c, --collection [collectionName]       Schematics collection to use (default: "@nestjs/schematics")
  --strict                                Enables strict mode in TypeScript. (default: false)
  -h, --help                              Output usage information.

nest new 一般不用带参数,取默认值就行。各个参数的意思在上面打印的注释中解释得很清晰了,比如 -g 和 -s 分别是跳过git初始化和跳过安装包;-p 可以指定包管理器;-l 指定 TS (默认值)或 JS 等等。

nest build

nest build 是打包项目的命令,执行后会在 dist 目录下生成编译后的代码。参数如下:

$ nest build -h
Usage: nest build [options] [app]
​
Build Nest application.
​
Options:
  -c, --config [path]    Path to nest-cli configuration file.
  -p, --path [path]      Path to tsconfig file.
  -w, --watch            Run in watch mode (live-reload).
  -b, --builder [name]   Builder to be used (tsc, webpack, swc).
  --watchAssets          Watch non-ts (e.g., .graphql) files mode.
  --webpack              Use webpack for compilation (deprecated option, use --builder instead).
  --type-check           Enable type checking (when SWC is used).
  --webpackPath [path]   Path to webpack configuration.
  --tsc                  Use typescript compiler for compilation.
  --preserveWatchOutput  Use "preserveWatchOutput" option when using tsc watch mode.
  -h, --help             Output usage information.

其中,

--config 和 --path 分别是指定 nest-cli 的配置文件和 tsc 配置文件的路径。

--builder [name] 是指定用什么编译,默认是 tsc 编译(--tsc),使用nest build --wepback则是使用 webpack ,也可以指定 swc 编译。tsc 不做打包;而webpack 会打包成单个 main.js 文件;使用swc编译得到:

swc.png

--watch 会监听文件的变动,默认只监听 ts、js 文件,加上 --watchAssets 会监听其他的文件(比如 .graphql)。

nest start

nest start 是启动 nest 应用的命令,一些参数和 nest build 是类似的。其中,--debug [hostport] 是启动 debug 模式 (带有 --inspect flag),参考:nodejs.org/en/docs/ins…

$ nest start -h
Usage: nest start [options] [app]
​
Run Nest application.
​
Options:
  -c, --config [path]        Path to nest-cli configuration file.
  -p, --path [path]          Path to tsconfig file.
  -w, --watch                Run in watch mode (live-reload).    
  -b, --builder [name]       Builder to be used (tsc, webpack, swc).
  --watchAssets              Watch non-ts (e.g., .graphql) files mode.
  -d, --debug [hostport]     Run in debug mode (with --inspect flag).
  --webpack                  Use webpack for compilation (deprecated option, use --builder instead).
  --webpackPath [path]       Path to webpack configuration.
  --type-check               Enable type checking (when SWC is used).
  --tsc                      Use typescript compiler for compilation.
  --sourceRoot [sourceRoot]  Points at the root of the source code for the single project in standard mode structures, or the default  
                             project in monorepo mode structures.
  --entryFile [entryFile]    Path to the entry file where this command will work with. Defaults to the one defined at your Nest's CLI  
                             config file.
  -e, --exec [binary]        Binary to run (default: "node").
  --preserveWatchOutput      Use "preserveWatchOutput" option when using tsc watch mode.
  -h, --help                 Output usage information.

nest info

查看项目信息,包括系统信息、Node和 pnpm 版本、Nest cli 版本、依赖版本:

$ nest info
​
 _   _             _      ___  _____  _____  _     _____ 
| \ | |           | |    |_  |/  ___|/  __ | |   |_   _|
|  | |  ___  ___ | |_     | |\ `--. | /  /| |     | |  
| . ` | / _ / __|| __|    | | `--. | |    | |     | |  
| |\  ||  __/__ | |_ /__/ //__/ /| __/| |_____| |_ 
_| _/ ___||___/ __|____/ ____/  ____/_____/___/ 
​
​
[System Information]
OS Version     : Windows 10.0.19045
NodeJS Version : v20.10.0
PNPM Version    : 8.12.0 
​
[Nest CLI]
Nest CLI Version : 10.3.0
​
[Nest Platform Information]
platform-express version : 10.3.1
schematics version       : 10.1.0
testing version          : 10.3.1
common version           : 10.3.1
core version             : 10.3.1
cli version              : 10.3.0

nest generate

nest 命令除了生成 application 外,还可以生成 class, module, controller, decorator, guard等。

比如我们生成一个模块 abc,可以看到:

$ nest generate module abc
CREATE src/abc/abc.module.ts (84 bytes)
UPDATE src/app.module.ts (490 bytes)
​
// src\app.module.ts
import { AbcModule } from './abc/abc.module';
@Module({
  imports: [UserModule, AbcModule],
  ...
​
// src\abc\abc.module.ts
import { Module } from '@nestjs/common';
@Module({})
export class AbcModule {}

继续生成 controller 和 service,会自动在 module 中引入:

$ nest generate controller abc
CREATE src/abc/abc.controller.ts (99 bytes)
CREATE src/abc/abc.controller.spec.ts (489 bytes)
UPDATE src/abc/abc.module.ts (166 bytes)
​
$ nest generate service abc
CREATE src/abc/abc.service.ts (91 bytes)
CREATE src/abc/abc.service.spec.ts (457 bytes)
UPDATE src/abc/abc.module.ts (237 bytes)

如果是要完整地生成一个模块的代码,可以直接用nest generate resource abc即可,接着选择 http 的 restful 风格的 api,就得到了一样的代码。

后记

Nest 借助 @nestjs/cli 包提供了各种 nest 命令,可以用于创建项目、开发构建、监听文件变动、编译项目等。常见的选项可以在 nest-cli.json 里进行配置。

掌握 @nestjs/cli 包的常用命令,对于学习 Nest 来说是必备的技能。