是否可以使用变量调用模块及其函数?
我有一条koa路线:
import Router from 'koa-router';
import one from '../modules/one.js';
import two from '../modules/two.js';
import three from '../modules/three.js';
router.get('/api/:m/:f', async function get(ctx) {
let { m, f } = ctx.request.params;
//how to call module.function using m.f()
});
export default router.middleware();
GET
将被调用以/api/one/add
这将触发模块one
及其功能add
。这可能吗?
如果你正在寻找类似的东西:
<code>const modules = {
one: require('../modules/one'),
two: require('../modules/two'),
three: require('../modules/three')
}
router.get('/api/:m/:f', async function get(ctx) {
let { m, f } = ctx.request.params;
//how to call module.function using m.f()
const module = modules[m];
const fn = module[f];
fn();
});
export default router.middleware();
</code>