5-3 服务器返回一个静态 html页面
searver/index.js
const Koa = require('koa')
const app = new Koa()
const { normal } = require('./tpl')
app.use(async (ctx,next)=>{
ctx.type='text/html;charset=utf-8'
ctx.body = normal
})
app.listen(8888)
server/tpl/index.js
const normalTpl=require('./normal')
module.exports={
normal:normalTpl
}
server/tpl/normal.js
module.exports=`
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>vuetest</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">This is </div>
<div class="col-md-6">This is normal</div>
</div>
</div>
</body>
</html>
`
5-4 集成模板引擎 koa 搭建初始模板目录
这里使用的是pug模板引擎+koa-views中间件,
npm i koa-views pug -S
1.searver/index.js
const Koa = require('koa')
const app = new Koa()
//
const views = require('koa-views')
const { resolve } =require('path')
//使用中间件
app.use(views(resolve(__dirname,'./views'),{
extension:'pug'
}))
app.use(async (ctx,next)=>{
//模板使用及传参
await ctx.render('index',{
you:'luck',
me:'lqs'
})
})
app.listen(8888)
server/views/index.pug
html
head
meta(charset='utf-8')
meta(name=viewport content="width=device-width,initial-scale=1")
title koa server pug
link(href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css")
body
.container
.row
.col-md-6
h1 Hi #{you}
p This is #{me}
.col-md-6
p 测试动态pug模板引擎
进一步优化目录结构
server/views/index.pug
extends ./layouts/default
block title
title koa douban shouye
block content
.container
.row
.col-md-6
h1 Hi #{you}
p This is #{me}
.col-md-6
p 测试动态pug模板引擎
server/views/layouts/default.pug
html
head
meta(charset='utf-8')
meta(name=viewport content="width=device-width,initial-scale=1")
block title
include ../includes/style
body
block content
include ../includes/script