Nestjs(二)cli 创建项目与基本使用

239 阅读1分钟

一、创建项目

  • 安装 cli

    $ npm i -g @nestjs/cli
    
  • 新建 nestjs 工程

    $ nest new [项目名称]
    
    # 严格模式
    $ nest new [项目名称] --strict
    
    ? **Which package manager would you ❤️  to use?** (Use arrow keys)
    ❯ npm 
      yarn 
      pnpm
    
  • 启动 nestjs 工程

    # 直接启动本地项目,支持热更新,一般开发跑这个
    $ npm run start:dev
    
    # 直接启动本地项目,不支持热更新
    $ npm run start
    
    # 其他命令看一看就知道
    # 跑起来之后 main.ts 中默认端口 3000,所以访问 http://localhost:3000/
    
  • 创建项目后 src 基本案例文件作用

    src
     ├── app.controller.spec.ts         // 基本控制器的单元测试样例
     ├── app.controller.ts              // 单个路由的基本控制器示例
     ├── app.service.ts                 // 带有单个方法的基本服务
     ├── app.module.ts                  // 应用程序的根模块
     └── main.ts                        // 应用程序入口文件。它使用 `NestFactory` 用来创建 Nest 应用实例。
    
  • 例如默认启动访问 http://localhost:3000/ 即可输出 Hello World!

    那么通过下面调整 app.controller.ts 即可通过不同路由输出同样的结果:

    import { Controller, Get } from '@nestjs/common';
    import { AppService } from './app.service';
    
    @Controller('/')
    export class AppController {
      constructor(private readonly appService: AppService) { }
    
      @Get('/hello')
      getHello(): string {
        return this.appService.getHello();
      }
    }
    
    // 访问地址 http://localhost:3000/hello
    
    import { Controller, Get } from '@nestjs/common';
    import { AppService } from './app.service';
    
    @Controller('/api')
    export class AppController {
      constructor(private readonly appService: AppService) { }
    
      @Get('/hello')
      getHello(): string {
        return this.appService.getHello();
      }
    }
    
    // 也支持去掉前面的 / ,结果一样
    // @Controller('api')
    // export class AppController {
    //   constructor(private readonly appService: AppService) { }
    
    //   @Get('hello')
    //   getHello(): string {
    //     return this.appService.getHello();
    //   }
    // }
    
    // 访问地址 http://localhost:3000/api/hello
    

二、常用指令

  • 查看指令

    dengzemiao@MacBook demo % 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   │ application │ Generate a new application workspace         │
          │ class         │ cl          │ Generate a new class                         │
          │ configuration │ config      │ 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 │
          └───────────────┴─────────────┴──────────────────────────────────────────────┘
    
  • 生成 user.controller.ts

    $ nest g co user
    

    image.png

    可以访问 http://localhost:3000/user/dzm 即可输出 Hello Dzm!

  • 生成 user.service.ts

    $ nest g s user
    

    image.png

    依然可以访问 http://localhost:3000/user/dzm 即可输出 Hello Dzm!

  • 如果考虑给一个模块生成 module.ts,那就必须最先执行,因为这是一个块的根入口,使用也只需要将这个module.ts 导入到别的根入口就行,就相当于整个块都导到另外一个模块中去了。

    例如:先执行创建 user.module.tsuser.module.ts 会被自动注入到 app.module.ts 中引用上,然后在执行上面创建 controller.tsservice.ts 等其他指令,这些 user 块的其他文件则会被自动注入到 user.module.ts 中,这样就能直接进行跑代码,而不需要二次调整,跑起来的结果跟上面单个案例一样。

    $ nest g mo user
    

    image.png

  • 以上步骤是一个一个生成的,还有个指令直接可以生成全套 CURD

    $ nest g resource user
    
    ? What transport layer do you use? (Use arrow keys)
    ❯ REST API 
      GraphQL (code first) 
      GraphQL (schema first) 
      Microservice (non-HTTP) 
      WebSockets 
      
    ? Would you like to generate CRUD entry points? (Y/n) Y
    # 下面有选了 Y/n 的效果,选了 Y 会有一些基础案例跟架子
    

    image.png