Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the ... spread syntax in javascript es6 named exports

I am attempting to import everything from a library as a hash, modify it, and re-export the modified hash, without knowing all of the named exports in a library. For example:

import * as reactBootstrap from 'react-bootstrap';  wrappedReactBootstrap = doFunnyThingsTo(reactBootstrap);  export {   ...wrappedReactBootstrap };  // or export wrappedReactBootstrap; 

My understanding of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export is that the following is not allowed by the spec. Could someone confirm?

Obviously, looping is out of the question, since export and import statements must be top level.

like image 622
Robert Balicki Avatar asked Apr 08 '17 21:04

Robert Balicki


People also ask

What is spread operator in JavaScript ES6?

The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.

What is named export in JavaScript?

Named exports allow us to share multiple objects, functions or variables from a single file and were introduced with the release of ES2015. Named exports are imported with curly braces in various files and must be imported using the name of the object, function or variable that was exported.

How many named exports can a ES6 JS file have?

One can have only one default export per file.


1 Answers

Object rest spread is stage 3 proposal and not a part of any spec (will probably be included in ES2018).

More importantly, export has syntax that mimics existing JS syntax but doesn't interpret { ... } as an expression. export syntax was strictly defined because ES2015 modules are supposed to be statically analyzed. This is one of their benefits, but it requires the developer to specify exports and imports explicitly.

Since { ...wrappedReactBootstrap } introduces dynamic export (it was used here exactly for this purpose), it isn't supported by ES2015 module export and it is very unlikely that it will be.

If it is necessary to provide dynamic behaviour for the export, it can be exported and imported as named or default object.

import * as reactBootstrap from 'react-bootstrap';  export default doFunnyThingsTo(reactBootstrap); 

And used like

import wrappedReactBootstrap from '...';  const { funny, thing } = wrappedReactBootstrap; 

Obviously, wrappedReactBootstrap object won't get the benefits of ES2015 modules this way, e.g. tree-shaking.

like image 93
Estus Flask Avatar answered Sep 18 '22 15:09

Estus Flask