设置应用程序

Nest is built with features from both ES6 and ES7 (decorators, async / await). It means, that the easiest way to start adventure with it is to use Babel or TypeScript. In this tutorial I will use TypeScript (it is not required) and I recommend everyone to choose this way too. Sample tsconfig.json file:

Nest 采用 ES6 和 ES7 (decorators, async / await)功能构建。也就是说使用Babel和TypeScript是开始Nest的最简单的方式。在这个教程中,我将使用TypeScript(非必需),我推荐大家也使用TypeScript。以下是一个简单的tsconfig.json文件样本:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6"
  },
  "exclude": [
    "node_modules"
  ]
}

Remember that emitDecoratorMetadata and experimentalDecorators properties have to be set to true. So let's start from scratch. Firstly, we have to create entry module of our application:

请记住将emitDecoratorMetadataexperimentalDecorators属性设置为true。 现在,我们开始吧,首先,我们必须先创建好应用程序的整个模块:

import { Module } from '@nestjs/common';

@Module({})
export class ApplicationModule {}

At this moment module metadata is empty, because we only want to run application (we don't have any controlles or components right now). Second step - make file (e.g. index.ts) and use NestFactory to create Nest application instance based on our module class.

import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

const app = NestFactory.create(ApplicationModule);
app.listen(3000, () => console.log('Application is listening on port 3000'));

That's all.

Express实例

If you want to have a full control of express instance lifecycle, you can simply pass already created object as a second argument of NestFactory.create() method, just like that:

如果你想完全控制express实例的生命周期,你可以将创建好的对象作为第二个参数传递给NestFactory.create()方法。如下所示:

import * as express from 'express';
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './modules/app.module';

const instance = express();
const app = NestFactory.create(ApplicationModule, instance);
app.listen(3000, () => console.log('Application is listening on port 3000'));

It means, that you can directly add some custom configuration (e.g. setup some plugins such as morgan or body-parser).

也就是说你可以直接添加自定义配置(比如:设置插件,如morgan或者body-parser)

results matching ""

    No results matching ""