简体   繁体   中英

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 (ie 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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM