我应该如何正确地在NestExpressApplication下使用nunjucks模板?
对于那些想要在NestJS框架中使用Nunjucks模板引擎的人,这里有一个最小化示例:
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as nunjucks from 'nunjucks';
import * as path from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const express = app.getHttpAdapter().getInstance();
const assets = path.join(__dirname, '..', 'assets'); // Directory with static HTML/CSS/JS/other files
const views = path.join(__dirname, '..', 'views'); // Directory with *.njk templates
nunjucks.configure(views, { express });
app.useStaticAssets(assets);
app.setBaseViewsDir(views);
app.setViewEngine('njk');
await app.listen(3000);
}
bootstrap();
import { join } from "path";
import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import * as nunjucks from "nunjucks";
import * as helmet from "helmet";
import { ApplicationModule } from "./app.module";
async function bootstrap() {
let options: any = {};
if (process.env.NODE_ENV === "product") options.logger = false;
const app = await NestFactory.create<NestExpressApplication>(
ApplicationModule,
options
);
app.use(helmet());
// app.useGlobalPipes(
// new ValidationPipe({
// whitelist: true,
// validationError: { target: false, value: false },
// }),
// );
app.useStaticAssets(join(__dirname, "..", "public"), { prefix: "/static/" });
const environment = nunjucks.configure(
[
join(__dirname, "..", "template"),
join(__dirname, ".", "system_template")
],
{
autoescape: true,
throwOnUndefined: false,
trimBlocks: false,
lstripBlocks: false,
watch: true,
noCache: process.env.NODE_ENV === "local" ? true : false,
express: app
}
);
app.engine("njk", environment.render);
app.setViewEngine("njk");
app.set("view cache", true);
await app.listen(process.env.APP_PORT);
}
bootstrap();
const express = app.getHttpAdapter().getInstance();
是做什么用的? - Ambassador Kosh.njk
文件时都会重新加载吗? - Ambassador Kosh