module - 在 ES6 模块中通过字符串访问导出函数

标签 module export ecmascript-6 babeljs

考虑以下因素:

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

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

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

我想到的一件事是将所有函数粘贴在一个对象上并单独导出它们。另一种选择是使用一些邪恶的 eval 东西。是否有通过字符串访问当前模块内的 ES6 导出的标准方法?

最佳答案

不太确定我遵循...

以下是 ES6 模块导入+导出的几个示例。其中有符合您要寻找的内容吗?

示例 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();

关于module - 在 ES6 模块中通过字符串访问导出函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29539006/

相关文章:

java - 多模块 spring boot 项目 messages.properties 未加载

java - Spring Boot 中是否有动态可加载模块的模式?

linux - BeagleBone Black 作为机器人的外部处理单元

Typescript 导出和再导出接口(interface)及其他数据

javascript - Redux 操作必须是普通对象

javascript - ES6 类的 getter 和 setter 实际上是什么?

python - `import directory.module` 和 `import module` 之间的区别

python - python 3.5 上的 PyHook

git - 如何在 SourceTree 中的两个 Git 提交之间导出所有更改的文件?

javascript - 在 ES 6 模块中重新导出默认值