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

3

我想在 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
2个回答

6
据我所知,只要在您的templates/views目录中有一个名为layout的文件夹,您就可以使用layout/index来实现与/layouts/index相同的功能。

我已经设置了一个git仓库作为一个工作示例,这样你就可以自己测试一下,看看是否需要更深入地了解任何内容。

编辑 6/27/2019:

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

通过创建一个基于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


谢谢您的回答,但正如我在问题中所指出的,我不想使用相对路径。 - woutr_be
你说得对!我完全误解了那个。请查看编辑后的答案。 - Jay McDoniel
1
看到你的编辑有点晚了,但你是对的。不过 Nest 会创建自己的 Express 实例,你可以通过 getHttpAdapter().getInstance() 访问它,然后就能设置 locals.basedir - woutr_be
两种方法都可行。如果没有传递实例,Nest将创建自己的实例。我看到Kamil在GitHub问题中回复了你,使用getHttpAdatper().getInstance()。我认为总体来说这是更好的方法,但知道两种方法都可以也很好。 - Jay McDoniel

2
在查阅了文档后,发现NestJS在内部使用了express,并通过getHttpAdapter().getInstance()让你可以访问底层实例。
有了这个认识,我们可以按照以下方式设置basedir
const express = server.getHttpAdapter().getInstance();
express.locals.basedir = join(__dirname, 'templates');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接