Accessing exported functions by string in ES6 modules

时光怂恿深爱的人放手 提交于 2019-12-05 00:16:37

问题


Consider the following:

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

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

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.

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?


回答1:


Not quite sure I follow...

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

Example 1

Producer:

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

Consumer:

import {one, two} from 'producer';

one();
two();

Example 2

Producer:

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

Consumer:

import * as producer from 'producer';

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

Example 3

Producer:

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

Consumer:

import producer from 'producer';

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

Example 4

Producer:

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

Consumer:

import {one, two} from 'producer';

one();
two();

Example 5

Producer:

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

Consumer:

import one, {two} from 'producer';

one();
two();


来源:https://stackoverflow.com/questions/29539006/accessing-exported-functions-by-string-in-es6-modules

工具导航Map