Skip to content Skip to sidebar Skip to footer

Generating Es6 Module Exports

I'm wanting to programmatically generate the exports for a module, is this possible in es6? Something along these lines: const ids = ['foo', 'bar', 'baz']; ids.forEach(id => {

Solution 1:

No, it's not. Exports and imports are required to be statically analysable in ES6 modules.

Not only is that no-top-level export declaration a syntax error, but also your attempt at declaring variables with dynamic names. The bracket notation is reserved for computed properties only.

So if you are going to programmatically generate module exports, you'll need to dynamically generate the module source text (as a part of your build process).

Solution 2:

You could export an object which has dynamic keys but then you would have to destructure it after the import.

const ids = ['foo', 'bar', 'baz'].reduce(...code to reduce to what you want);
export default ids; // { FOO: 'foo', BAR: 'bar', BAZ: 'baz' }
import ids from'./ids'const { BAR } from ids;

Post a Comment for "Generating Es6 Module Exports"