koa-router动态导入的路由

我的项目结构:

在这里插入图片描述

入口文件:app.js

 // 引入同级 routes/index.js
const routes = require('./routes')
// use 一下
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'){ 
			//读取的时候会将当前目录的 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

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;

猜你喜欢

转载自blog.csdn.net/weixin_45292658/article/details/107104408