3

How come I can write

export { function1, function2 };

But I can't write

const funcs = { function1, function2 };
export funcs;

Isn't it semantically the same thing?

Is there any way to export all properties from an object without listing them all one by one? I want to be able to import the module as a whole (i.e. import Utils from './utils') and as individual functions (import { function1 } from './util'), but it won't let me use my default export object for normal export:

const Util = {
   ...
};

export ???; // <- what do I put here? do I really have to list every field in Util?
export default Util;
riv
  • 6,846
  • 2
  • 34
  • 63
  • 1
    In `export { function1, function2 };`, the brackets aren't an "object". They're not the same as `const funcs = { function1, function2 };` – Cerbrus Dec 06 '17 at 10:58
  • Well that's confusing, using object syntax for something that isn't an object -_- – riv Dec 06 '17 at 10:59
  • 1
    `if(condition) { func(); }` <-- Same brackets. But that's not an object, either. – Cerbrus Dec 06 '17 at 11:00
  • 1
    Possible duplicate of [ES6 export all values from object](https://stackoverflow.com/questions/29844074/es6-export-all-values-from-object) – maazadeeb Dec 06 '17 at 11:00
  • Thanks @MaazSyedAdeeb, guess no solution then unless I use CommonJS. – riv Dec 06 '17 at 11:02

1 Answers1

6

export { function1, function2 }; does not export an object. It is shorthand for

export {
  function1 as function1,
  function2 as function2
};

which does export the function1 and function2 variables from the module scope as named exports.

Is there any way to export all properties from an object without listing them all one by one?

No. Just don't start with an object, but export the functions individually (using the named export function …(…) {…} syntax). Do not create const Utils = {…}.

I want to be able to import the module as a whole (i.e. import Utils from './utils')

You don't need an object in the default export for that. Just import the module namespace object instead:

import * as Utils from './utils';
Bergi
  • 630,263
  • 148
  • 957
  • 1,375