Javascript (ES6) Modules: Is it possible to export a variable with a dynamic name? [duplicate]
Asked Answered
A

1

5

In ES6 I can export a simple foo constant:

export const foo = 1;

I can also convert the value of that export (1) to a variable, and export that:

const fooValue = 1;
export foo = fooValue;

But my question is, is there any way I can convert the key of the export (foo) in to a variable:

const fooLabel = 'foo';
const fooValue = 1;
export something(fooLabel) = fooValue;

Or do exports always have to explicitly named?

Arquit answered 26/9, 2016 at 17:45 Comment(0)
M
11

You won't be able to use named exports. It's easy enough to export a single object with dynamically generated keys though:

let obj = {};

obj[fooLabel] = fooValue;

export default obj;
Macneil answered 26/9, 2016 at 17:48 Comment(3)
Right, but unfortunately then I can't do import {foo} from 'obj' :(Arquit
@Arquit - Nope. But you can import and then destructure it in another statement.Macneil
Yeah, not quite the interface I was hoping for, but hey it still it beats the crap out of ES5 (non-) importsArquit

© 2022 - 2024 — McMap. All rights reserved.