我的项目结构:
入口文件:app.js
const routes = require('./routes')
app.use(routes.routes(), routes.allowedMethods())
自动导入路由:routes/index.js
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'){
console.log("routes module must not be 'index.js' " )
}
return file !== '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
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;