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?
Use named exports to export a function in JavaScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file. js' . You can use as many named exports as necessary in a file.
All CommonJS and AMD modules are presented to ES6 as having a default export, which is the same thing that you would get if you asked require() for that module—that is, the exports object. ES6 modules were designed to let you export multiple things, but for existing CommonJS modules, the default export is all you get.
To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With