ngATL Conference Atlanta, GA

NestJS on 2018 ngATL Conference Atlanta, GA

NestJS 2018 ngATL

LEARN MORE

MVC

Nest uses express library under the hood, therefore every tutorial about MVC (Model-View-Controller) pattern in express concerns Nest as well. Firstly, let's clone a Nest starter project:

JavaScript TypeScript

$ git clone https://github.com/nestjs/typescript-starter.git project
$ cd project
$ npm install
$ npm run start

$ git clone https://github.com/nestjs/javascript-starter.git project
$ cd project
$ npm install
$ npm run start

In order to create a simple MVC app, we have to install a template engine:


$ npm install --save jade

I have chosen jade because it's the most popular engine at the moment, but personally, I prefer a Mustache. Once the installation process is completed, we need to configure the express instance using following code:

main.ts
JavaScript TypeScript
TypeScript

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

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);

  app.use(express.static(path.join(__dirname, 'public')));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');

  await app.listen(3000);
}
bootstrap();

We told express that the public directory will be used for storing static assets, views will contain templates, and a jade template engine should be used to render an HTML output.

Now, let's create a views directory and an index.jade template inside this folder. Inside template, we are gonna print a message passed from the controller:

index.jade
TypeScript

html
head
body
  p= message

Afterwards, open the app.controller file and replace the root() method with the following code:

app.controller.ts
JavaScript TypeScript
TypeScript

@Get()
root(@Res() res) {
  res.render('index', { message: 'Hello world!' });
}
TypeScript

@Get()
@Bind(Res())
root(res) {
  res.render('index', { message: 'Hello world!' });
}
Hint In fact, when Nest detects @Res() decorator, it injects express response object. Learn more about its abilities here.

That's all. While the application is running, open your browser and navigate to http://localhost:3000/. You should see the Hello world! message.

Sponsors

Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here. Thanks!

Become a sponsor