在 NestJS 中为 Pug 设置 "basedir" 选项

Set "basedir" option for Pug in NestJS

我正在尝试在 NestJS 中使用 pug 布局,但是当从绝对路径扩展布局时,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

据我所知,只要 layouttemplates/views 目录中的一个文件夹,您只需使用 layout/index 就可以实现与 /layouts/index 相同的功能.

我已经 set up a git repo 作为一个工作示例,因此您可以自己测试它,看看我是否需要更深入地了解任何内容。

编辑 2019 年 6 月 27 日:

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

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

我的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

在浏览了文档之后,NestJS 在幕后使用了一个 express,并允许您使用 getHttpAdapter().getInstance().

访问底层实例

牢记这一点,我们可以按如下方式设置 basedir

const express = server.getHttpAdapter().getInstance();
express.locals.basedir = join(__dirname, 'templates');