nestjs: mvc(ejs + controller)
一个基于 ejs 和 nestjs 的渲染架构
安装
# 利用 yarn 全局安装
yarn add global @nestjs/cli
# 有个报错,需要安装下面的 Error: Collection "@nestjs/schematics" cannot be resolved.
yarn global add @nestjs/schematics
# 检测
nest --version
开始
开始一个新的项目: https://github.com/aric-tpls/nestjs-ejs
# 在当前目录新建项目
nest new .
yarn add ejs
main.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path'; // new
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// set view engine
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setLocal('shared', join(__dirname, '..', 'views/shared'));
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
pages/index.ejs
利用 locals 设置 一个 shared 的全局变量
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hello</title>
</head>
<body>
<!-- include header -->
<%- include(`${shared}/partials/header`) %>
<%= message %>
</body>
</html>
参考
- https://docs.nestjs.com/recipes/serve-static
- https://blog.logrocket.com/how-to-use-ejs-template-node-js-application/
- https://stackoverflow.com/questions/58165258/ejs-including-partials-in-nested-directories-relative-to-set-views-path
- https://expressjs.com/en/4x/api.html#app.locals
- https://www.digitalocean.com/community/tutorials/how-to-use-ejs-to-template-your-node-application