Generating es6 module exports

Viewed 1822

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 => {
    export const [id.toUpperCase()] = id;
});
2 Answers

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;
Related