┌─/
├─📂routes
│ ├─📄A.ts             路由配置文件A
│ ├─📄B.ts          路由配置文件B
│ └─📄index.ts            路由注册文件
└─📄app.ts
// app.ts
import Koa from "koa";
import { autoRouter } from "./routes";

const app: Koa = new Koa()

autoRouter(app)

export default app

// routes/index.ts
import fs from "fs";
import path from "path";
import type Koa from "koa";

/**
 * 自动导入并注册路由
 * @param {Koa} app Koa原型
 */
export const autoRouter = async (app: Koa) => {
  const dir = path.join(__dirname); // 获取资源完整路径
  const fileList = fs.readdirSync(dir); // 读取目录下的文件

  // 过滤掉routes下的无关文件,精确过滤需要自己写
  const filesToImport = fileList.filter((file) => {
    return fs.statSync(path.join(dir, file)).isFile() && file !== "index.ts";
  });
  
  // 当存在路由配置文件时,自动导入并注册
  if (filesToImport.length > 0) {
    filesToImport.forEach(async (file) => {
      const module = await import(path.join(dir, file));
      const route = module.default;
      if (route && typeof route.routes === "function") {
        app.use(route.routes()); // 注册路由
      }
    });
  }
};