admin管理员组

文章数量:1406727

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

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;
});
Share Improve this question asked Mar 8, 2016 at 18:35 TomTom 44.9k4 gold badges43 silver badges61 bronze badges 1
  • possibly related: What qualifies as being a dynamic export in ES6 – Bergi Commented Mar 8, 2016 at 18:46
Add a ment  | 

2 Answers 2

Reset to default 8

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 puted 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).

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;

本文标签: javascriptGenerating es6 module exportsStack Overflow