33

See question title. I found a great reference for the forms of export available, but I have not seen what I'm looking for.

Is it possible to do something like the following?

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
export * as Constants from './constants.js';

I.e. this would provide a named export Constants inside of index.js containing all of the named exports from constants.js.


This answer seems to indicate it's not possible in TypeScript; is the same true for pure JavaScript?

(This example is a bit contrived; in reality I'm trying to have a prop-types.js module that uses named exports for internal use within the React package, but also exports the prop type definitions under PropTypes for external consumption. I tried to simplify for the sake of the question.)

vergenzt
  • 9,669
  • 4
  • 40
  • 47
  • possible duplicate of [Is it possible to export the result of “import * as” in ES2015?](https://stackoverflow.com/q/33928698/1048572) – Bergi Mar 11 '19 at 16:07

4 Answers4

40

No, it's not allowed in JS either, however there is a proposal to add it. For now, just use the two-step process with importing into a local variable and exporting that:

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
import * as Constants from './constants.js';
export {Constants};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
30

Today in 2019, it is now possible.

export * as name1 from …;
NPP
  • 416
  • 4
  • 3
4

The proposal for this spec has merged to ecma262. If you're looking for this functionality in an environment that is running a previous JS, there's a babel plugin for it! After configuring the plugin (or if you're using ecma262 or later), you are able to run the JS in your question:

// file: constants.js
export const SomeConstant1 = 'yay';
export const SomeConstant2 = 'yayayaya';

// file: index.js
export * as Constants from './constants.js';

// file: component.js
import { Constants } from './index.js';

const newVar = Constants.SomeConstant1; // 'yay'
josephemswiler
  • 401
  • 4
  • 5
0
// file: index.js
// note, this doesn't have to be at the top, you can put it wherever you prefer
import * as AllExportsFromThisModule from "./index.js"; // point this at the SAME file
export default AllExportsFromThisModule;

export const SOME_CONSTANT = 'yay';
export const SOME_OTHER_CONSTANT = 'yayayaya';
Brent Larsen
  • 1,042
  • 8
  • 10