Is it possible to export the result of "import * as" in ES2015?
Asked Answered
T

1

11

In ES2015, it's possible to import an entire module as an object whose properties are the module's exports:

import * as name from 'module';

I find this to be extraordinarily useful for namespacing and use it all the time.

It's also possible to re-export other modules' exports:

export { name } from 'module'; // selectively
export * from 'other-module'; // indiscriminately

Now I'm trying to write a library with namespacing in this style. The intuitive way of collecting everything in the top-level module would be like this:

export * as name from 'module';

But that doesn't seem to work; Babel and Rollup both reject it.

I could import the module as an object, create a clone by iterating over its keys, and export that, but then it would just be a plain old dynamic object, so I would lose the great advantages Rollup provides.

So, is there really no way to do this with the declarative module syntax? It seems to me like there's no excuse for that.

Tyro answered 26/11, 2015 at 0:20 Comment(3)
I don't understand what you are trying to accomplish with export * as name from 'module';. How would you be planning to use such an export? Importing * always requires the namespace as X, so whatever name you specify in the export statement would be irrelevant anyway--right?Inconvenient
@torazaburo name is the name the module object is exported with. For instance, if module "abc" contains export * as xyz from 'xyz', and you import * as abc from 'abc', you'll be able to access "xyz"s exports via abc.xyz.Tyro
possible duplicate of ES6 module syntax: is it possible to export * as Name from …?Forgot
F
23

No, this was simply missed in ES6. There is a stage 1 proposal to add these, though, and rollup will consider implementing it.

Until then, you will need to use two declarations and a local binding, altough there's no need to clone the object:

import * as name from 'module';
export { name };
Forgot answered 26/11, 2015 at 5:10 Comment(5)
Oh, fantastic! That's exactly what I needed! I didn't realize you needed curly braces to do this, since MDN doesn't include them.Tyro
Where does MDN not use curly braces? Of course, in many other export declarations (defaults, vars, etc) they're not needed.Forgot
At the top of the page for the export statement, it lists the syntax for named exports as export name1, name2, ..., nameN; with no braces. Additionally, in the description, it gives this example: export myFunction; // exports a function declared earlierTyro
Uh, those docs seem to be scarce. Better have a look at 2ality.com/2014/09/es6-modules-final.html (and I'll go fix MDN).Forgot
By the way, if you check and don't see the problem, it's because I just changed it. First time editing, hope I didn't mess up horribly.Tyro

© 2022 - 2024 — McMap. All rights reserved.