nestjs: mvc(hbs + controller)

基于 nestjs,利用 handlebars 作为模板引擎
更新于: 2023-09-01 16:32:26

安装

# 利用 yarn 全局安装
yarn add global @nestjs/cli
# 有个报错,需要安装下面的 Error: Collection "@nestjs/schematics" cannot be resolved.
yarn global add @nestjs/schematics
# 检测
nest --version

开始

开始一个新的项目: https://github.com/aric-tpls/nestjs-hbs

# 在当前目录新建项目
nest new .
yarn add hbs

main.ts

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

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

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

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

index.hbs

./views/index.hbs 这个 view 就在根目录下。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>App</title>
  </head>
  <body>
    {{ message }}
  </body>
</html>

app.controller.ts

import { Get, Controller, Render } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  @Render('index')
  root() {
    return { message: 'Hello world!' };
  }
}

hbs 的 partials 检测(watch)

需要用到 hbs-utils,否则无法检测到。

nest-cli.json 不需要任何的配置,即可生效。

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

const hbsutils = require('hbs-utils')(hbs);
const cwd = process.cwd();

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  // set public
  app.useStaticAssets(join(cwd, 'public'));
  app.setBaseViewsDir(join(cwd, 'views'));

  // hbs + hbs options
  app.setViewEngine('hbs');
  hbsutils.registerPartials(join(cwd, 'views/partials'));
  hbsutils.registerWatchedPartials(join(cwd, 'views/partials'));

  await app.listen(3000);
}

bootstrap();

参考