有勇气的牛排博客

Typescript Express 框架 04 前端html 模板引擎

有勇气的牛排 273 TypeScript 2024-11-24 00:13:52

1 原生方案

1.1 server.ts 配置

src/server.ts

// 配置静态文件夹 app.use(express.static(path.join(__dirname, 'templates'))); // 路由返回 HTML 页面 app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'templates', 'index.html')); });

1.2 html 页面

src/templates/index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 首页 </body> </html>

2 EJS 模板引擎

2.1 安装

npm install ejs

2.2 server.ts 配置

src/server.ts

// 设置视图引擎为 EJS app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'templates')); // 路由返回动态渲染的 HTML 页面 app.get('/', (req, res) => { res.render('index', { title: '有勇气的牛排博客' }); });

2.3 html 页面

src/templates/index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= title %></title>
</head>
<body>
<h1>欢迎来到 <%= title %>!</h1>
<p>这个页面使用 EJS 模板引擎加载.</p>
</body>
</html>

image.png


留言

专栏
文章
加入群聊