Accessing exported functions by string in ES6 modu

2019-03-30 03:00发布

问题:

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