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

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

入口文件:app.js

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

自动导入路由: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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章