如何更简便地导入目录下所有模块?现有import方案过于复杂
简化ES模块批量导入路由的方法
你用require的写法确实简洁,而ES模块的import因为是异步特性,需要处理Promise,但可以通过以下方式简化:
1. 统一批量处理Promise(推荐)
用Promise.all一次性处理所有模块的导入,避免每个import单独写then,代码更整洁:
场景1:路由模块用默认导出(export default router)
import { readdirSync } from 'fs'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; // ES模块中获取__dirname(CommonJS环境可省略这段) const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); Promise.all( readdirSync(join(__dirname, 'routes')) .filter(file => file.endsWith('.js')) // 过滤非JS文件 .map(file => import(join(__dirname, 'routes', file))) ).then(modules => { modules.forEach(module => app.use('/api', module.default)); });
场景2:路由模块用命名导出(export const routerA/export const routerB)
用Object.values直接提取所有导出的路由,替代Object.entries.map(entry => entry[1]):
Promise.all( readdirSync(join(__dirname, 'routes')) .filter(file => file.endsWith('.js')) .map(file => import(join(__dirname, 'routes', file))) ).then(modules => { modules.forEach(module => { Object.values(module).forEach(router => app.use('/api', router)); }); });
2. 用async/await让代码更线性
如果在异步函数中,可以用await替代then,逻辑更清晰:
import { readdirSync } from 'fs'; import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); async function registerRoutes() { const routeFiles = readdirSync(join(__dirname, 'routes')).filter(file => file.endsWith('.js')); const modules = await Promise.all(routeFiles.map(file => import(join(__dirname, 'routes', file)))); modules.forEach(module => { // 兼容默认导出和命名导出 if (module.default) { app.use('/api', module.default); } else { Object.values(module).forEach(router => app.use('/api', router)); } }); } registerRoutes();
原写法复杂的原因
你的代码在map里每个import单独触发then,没有批量处理Promise;同时Object.entries(value).map(entry => entry[1])可以直接用Object.values(value)简化,减少了冗余操作。
内容的提问来源于stack exchange,提问作者Scogur
相关产品推荐
相关产品推荐

