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