node Koa框架+nunjucks模版開發簡易的後臺

 初步文件結構以下css



開發所需包 package.json 以下:html

{
  "name": "koa_",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "koa": "^2.6.1",
    "koa-nunjucks-2": "^3.0.2",
    "koa-router": "^7.4.0",
    "koa-static": "^5.0.0",
    "nunjucks": "^3.1.3"
  }
}
複製代碼

index文件web

const path = require('path');
const Koa = require('koa');
//沒必要引入nunjucks  直接用這個中間件就行
const koaNunjucks = require('koa-nunjucks-2');
const loadStatic = require('koa-static');
const Router = require('koa-router');

//引入路由分支
const index = require('./router/index');

const router = new Router();
const app = new Koa();
//加載HTML
app.use(koaNunjucks({
    //文件後綴
    ext: 'html',
    //文件位置
    path: path.resolve(__dirname, 'public'),
    //模版配置
    nunjucksConfig: {
        autoescape: true,
        trimBlocks: true,
        web:{
            async:true
        },
        lstripBlocks : true,
        watch:true//當模板變化時從新加載。使用前請確保已安裝可選依賴 chokidar。
    }
}));

//其餘文件內接口 引入
router.use('/index', index.routes(), index.allowedMethods());
app.use(router.routes());

//加載靜態文件 css img js
app.use(loadStatic(path.resolve(__dirname, 'public')));
//監聽3000端口
app.listen(3000);

複製代碼

接口json

const Router = require('koa-router');
var router = new Router();
router.get('/',async (ctx, next) => {
            //返回的模版名字是index   data是模版傳值
            ctx.render('html/index',{data:[1,2,3]});
        })
module.exports=router;複製代碼

index.html 文件bash

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title>Title</title>
    <link rel="stylesheet" href="../css/index.css">
</head>
<body>
<!--<img src="../img/aa.jpg" alt="">-->
{{ data}}

{% for item in data %}
    <li>{{ item }}</li>
    <li>....{{item}}....</li>
{% endfor %}


<script src="../js/index.js"></script>
</body>
</html>複製代碼

訪問本地 localhost:3000/index/
app

相關文章
相關標籤/搜索