23

Say, I have an object like {foo: 5, bar: 10} and I wanna export foo and bar from it separately, then when I do import {foo} from './path/to/file';

I could get foo equal to 5, as if I did export const foo = 5; export const bar = 10;

How can I do it?

2
  • export const foo = obj.foo; export const bar = obj.bar;... Commented Jun 6, 2016 at 14:46
  • You really should do export const foo = 5; export const bar = 10; Commented Jun 6, 2016 at 17:43

1 Answer 1

45

Exported values need their own top-level variable name. The easiest option might be something like this:

const obj = {foo: 5, bar: 10};

export const {foo, bar} = obj;

Really though, if the object is already declared in the file, you may be better off declaring the exports with the values directly.

Sign up to request clarification or add additional context in comments.

6 Comments

What if I wanted to export default obj.foo only. What would be my alternatives?
@Telokis I'm not sure what you're describing? export default obj.foo; is valid JS.
Nevermind, the issue is because obj.foo is dynamically generated. Thus, we have to module.export it and eslint isn't pleased with that. Thanks anyway
@Telokis Probably best not to use named exports for that then. If it's not a static list, the only time I'd recommend using named exports is if it's a non-static list that could be constructed at build time rather than runtime. If it's dynamically generated based on some runtime source, I'd recommend exporting a single object and using that dynamically instead.
@eczn With ES modules, the names being exported have to be known statically, so you cannot pull them from an object.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.