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:
$ 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:
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:
html
head
body
p= message
Afterwards, open the app.controller file and replace the root() method with the following code:
@Get()
root(@Res() res) {
res.render('index', { message: 'Hello world!' });
}
@Get()
@Bind(Res())
root(res) {
res.render('index', { message: 'Hello world!' });
}
Hint In fact, when Nest detects@Res()decorator, it injects expressresponseobject. 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.