首页 > 解决方案 > 在 NestJS 中为 Pug 设置“basedir”选项

问题描述

我正在尝试在 中使用pug布局NestJS,但是当从绝对路径扩展布局时,pug需要basedir设置该选项。

在 ExpressJS 中你会使用app.locals.basedir = ...,在 NestJS 中什么是等价的?

const server = await NestFactory.create<NestExpressApplication>(AppModule);
server.setViewEngine('pug');
server.setBaseViewsDir(join(__dirname, 'templates', 'views'));
await server.listen(config.server.port);

在视图中使用extends /layouts/index会抛出以下内容;the "basedir" option is required to use includes and extends with "absolute" paths.

我不想使用相对路径,因为这很快就会变得非常混乱。例如extends ../../../layouts/index

标签: node.jspugnestjs

解决方案


据我所知,您可以实现/layouts/index与仅使用目录layout/indexlayout的文件夹相同的功能templates/views

我已经建立了一个 git repo作为一个工作示例,这样你就可以自己测试它,看看我是否需要更深入地了解任何事情。

编辑2019 年 6 月 27 日:

谢谢,我误解了你最初的问题。

使用基于创建和表达的应用程序,您可以发送一个express serverNestFactory使用该服务器实例,而不是让 Nest 为您创建一个普通实例。从这里您可以express server像往常一样设置并获得所需的功能。我已经修改了 git repo 以便能够更好地测试场景并相信这就是您要寻找的。

我的main.ts

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

async function bootstrap() {
  // Creating and setting up the express instanced server
  const server = express();
  server.locals.basedir = join(__dirname, '..', 'views');
  // Using the express server instance in the nest factory
  const app = await NestFactory.create<NestExpressApplication>(AppModule, new ExpressAdapter(server));
  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('pug');
  await app.listen(3000);
}
bootstrap();

总的来说文件夹设置是这样的

src
|-app.controller.ts
|-app.module.ts
|-app.service.ts
|-main.ts
views
|-hello
  |-home.pug
|-message
  |-message.pug
|-templates
  |-layout.pug

home.pugmessage.pug文件的开头是extends /templates/layout


推荐阅读