Setup Application

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:

{
  "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:

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 instance

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:

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).

results matching ""

    No results matching ""