koa自动导入全部路由,koa-router动态添加路由,js做的koa-router动态导入的路由没使用ts语法

这是我的项目结构
在这里插入图片描述

入口文件:app.js

1
2
3
const routes = require('./routes') // 引入同级 routes/index.js
// routes
app.use(routes.routes(), routes.allowedMethods()) // use 一下

自动导入路由:routes/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const router = require('koa-router')(); //引入并实例化
const fs = require('fs');
const path = require('path');

function loadRoutes(filePath) { //封装递归

    const files = fs.readdirSync(filePath); //将当前目录下 都读出来

    files.filter(file => { // 过滤
       
        if(filePath !== __dirname && file === 'index.js'){ //读取的时候会将当前目录的 index.js 也读取出来,这个不需要,如果拿到别的地方可以不加这个判断
           
            console.log("routes module must not be 'index.js' " )
           
        }
       
        return file !== 'index.js'
       
    }) // 将 index.js 过滤掉,路由名字一律不能用 index.js 命名,否则不生效,我这里边的 index.js 如果拿到外面就不用添加这个判断了 ...
        .forEach(file => {
           
            let newFilePath = path.join(filePath,file);
           
            if(fs.statSync(newFilePath).isDirectory()){ // 是目录
           
                loadRoutes(newFilePath); // 递归
               
            }else{ // 是文件
           
                let route = require(newFilePath);
               
                //注册路由
                router.use(route.routes())
                router.use(route.allowedMethods())
            }
        })

}

//启动
loadRoutes(__dirname);

module.exports = router;

路由 Demo :routes/default/home.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const router = require('koa-router')()

router.get('/', async (ctx, next) => {
    await ctx.render('default/index', {
        title: 'Hello Koa 2!'
    })
})

router.get('/string', async (ctx, next) => {
    ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
    ctx.body = {
        title: 'koa2 json'
    }
})

module.exports = router;