riv
riv

Reputation: 7324

ES6 export an existing object

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;

Upvotes: 3

Views: 2132

Answers (1)

Bergi
Bergi

Reputation: 664195

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

Upvotes: 6

Related Questions