【问题标题】:Set "basedir" option for Pug in NestJS在 NestJS 中为 Pug 设置“basedir”选项
【发布时间】:2019-06-28 10:58:17
【问题描述】:

我正在尝试在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

【问题讨论】:

    标签: node.js pug nestjs


    【解决方案1】:

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

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

    编辑 2019 年 6 月 27 日:

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

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

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

    【讨论】:

    • 感谢您的回答,但就像我在问题中指出的那样,我不想使用相对路径。
    • 你是对的!我完全误解了这一点。请参阅编辑以获取更新的答案。
    • 看到你的编辑有点晚了,但你是对的,但是 Nest 会创建它自己的 Express 实例,你可以使用 getHttpAdapter().getInstance() 访问它,从那里你可以设置 locals.basedir .
    • 两者都是可行的选择。如果还没有传递给 Nest,Nest 将创建自己的实例。我看到 Kamil 用 getHttpAdatper().getInstance() 回复了你的 GitHub 问题。我认为总体而言是一种更好的方法,但很高兴知道这两种方法都有效。
    【解决方案2】:

    查看文档后,NestJS 在后台使用 express,并通过 getHttpAdapter().getInstance() 让您访问底层实例。

    记住这一点,我们可以如下设置basedir

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

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 2022-12-06
      • 2019-09-04
      • 2020-01-25
      • 2013-05-07
      • 2016-11-24
      相关资源
      最近更新 更多