본문 바로가기
Research/Nest.js

nestjs_view 엔진 적용하기(hbs)

by RIEM 2023. 4. 13.
728x90
npm install --save hbs

handlebars 뷰 엔진 설치

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';

async function bootstrap() {
  // const app = await NestFactory.create(AppModule);
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  /**
   * for applying MVC pattern
   * _dirname : current path
   */
  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

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

main.ts에 정적 파일 경로 및 뷰엔진 세팅

public, views 폴더를 만들어주고, 각자 파일을 만들어준다.

{{! views/index.hbs }}
<html>
  <head>
    <meta charset='utf-8' />
    <title>App</title>
    <link href='css/styles' rel='stylesheet' />
  </head>
  <body>
    <h1>Title</h1>
    {{message}}
  </body>
</html>

 

@Controller('news')
export class NewsController {
  constructor(private readonly newsService: NewsService) {}

  @Get()
  getAllNews() {
    return this.newsService.getAllNews();
  }

  @Get('/home')
  @Render('index')
  test() {
    return { message: 'Hi guys' };
  }
  
  ...

임시로 controller에 테스트 handler를 만들어주었다.

/* public/css */
h1 {
  color: salmon;
}

.test {
  color: red;
}

public 폴더 내 CSS 파일도 만들어주었다.

 

요청을 해보니 HTML은 잘 렌더링되는데, CSS는 실패하고 있는 상황이다.

<html>
  <head>
    <meta charset='utf-8' />
    <title>App</title>
    <link href='styles.css' rel='stylesheet' />
    <style>
      h1 { color: salmon;}
    </style>
  </head>
  <body>
    <h1>Title</h1>
    <div class='test'>hello</div>{{message}}

    <script src='js/scripts.js'></script>
  </body>
</html>

일단 html 스크립트 내에 넣어주었다. 중요한 문제가 아니라서 일단 넘어가도록 하겠다.

Ref

- https://docs.nestjs.com/techniques/mvc

728x90

댓글