在ES6模块中按字符串访问导出的函数 [英] Accessing exported functions by string in ES6 modules

查看:177
本文介绍了在ES6模块中按字符串访问导出的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

exports['handleEvent']('event');

export function handleEvent(event) {
  // do something with `event`
}

这在使用babel转换节点模块时有效,因为它将所有内容粘贴在导出对象上.原始ES6中是否有导出对象的概念?我希望能够使用其名称的字符串来调用方法.

This works when using babel to transpile node modules because it sticks everything on the exports object. Is there any concept of the exports object in vanilla ES6? I want to be able to call a method using a string of its name.

我想到的一件事就是将所有功能粘贴在一个对象上,然后分别导出它们.另一种选择是使用一些邪恶的评估材料.是否有任何标准方法可以通过字符串访问当前模块中的ES6导出?

One thing I've thought of is just sticking all the functions on an object and exporting them individually. Another option would be to use some evil eval stuff. Are there any standard methods for accessing ES6 exports within the current module by string?

推荐答案

不太确定我会遵循...

Not quite sure I follow...

以下是ES6模块导入+导出的一些示例.他们中的任何一个都符合您的需求吗?

Here are a few examples of ES6 module importing + exporting. Do any of them match what you're looking for?

示例1

制作人:

export function one() { return 1 };
export function two() { return 2 };

消费者:

import {one, two} from 'producer';

one();
two();

示例2

制作人:

export function one() { return 1 };
export function two() { return 2 };

消费者:

import * as producer from 'producer';

producer.one(); // or producer['one']()
producer.two();

示例3

制作人:

export default {
  one() { return 1 },
  two() { return 2 }
};

消费者:

import producer from 'producer';

producer.one(); // or producer['one']()
producer.two();

示例4

制作人:

export default {
  one() { return 1 },
  two() { return 2 }
};

消费者:

import {one, two} from 'producer';

one();
two();

示例5

制作人:

export default function() { return 1 };
export function two() { return 2 };

消费者:

import one, {two} from 'producer';

one();
two();

这篇关于在ES6模块中按字符串访问导出的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆