The preliminary document structure is as follows




The package package.json required for development is as follows:

{
  "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"}}Copy the code

The index file

const path = require('path');
const Koa = require('koa'); Const koaNunjucks = require('koa-nunjucks-2');
const loadStatic = require('koa-static');
const Router = require('koa-router'); // import route branch const index = require('./router/index'); const router = new Router(); const app = new Koa(); // load HTML app.use(koaNunjucks({ext:'html'Path: path.resolve(__dirname,'public'NunjucksConfig: {autoescape:true,
        trimBlocks: true,
        web:{
            async:true
        },
        lstripBlocks : true,
        watch:true// Reload when the template changes. Make sure optional dependencies Chokidar is installed before using. }})); Router.use ('/index', index.routes(), index.allowedMethods()); app.use(router.routes()); Img js app.use(loadStatic(path.resolve(__dirname,'public'))); App.listen (3000);Copy the code

interface

const Router = require('koa-router');
var router = new Router();
router.get('/',async (CTX, next) => {// return the template name as index data ctx.render('html/index'}, {data: [1, 2, 3]); }) module.exports=router;Copy the code

The index.html file

<! 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 indata %} <li>{{ item }}</li> <li>.... {{item}}.... </li> {% endfor %} <script src=".. /js/index.js"></script>
</body>
</html>Copy the code

Access localhost:3000/index/