Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 - Exporting module with a getter

would like to export a module that get's the module's definition from some global object.

It's something like:

export {
  get DynamicModule() {
    return __globalFluxStorage.state.property.property.property.property
  }
}

...

import {DynamicModule} from 'dynamic-module'

We have a complex flux storage and DynamicModule is just a means of accessing __globalFluxStorage.state.property.property.property.property without the need to type in the long property accessor. Is this possible? Thanks.

Edit:

Since I am using babel, tried something like this:

Object.defineProperty(module.exports, "Forms", {
  get: function() {
    return __globalFluxStorage.state.property.property.property.property
  }
});

But does not work, i.e. {DynamicModule} is undefined

like image 775
user3367701 Avatar asked Feb 03 '16 11:02

user3367701


People also ask

What is difference between export and export default?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.

Can a module have more than one export?

Description. Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.

Why would you create a default export in a module?

Export default is used when there is only one export to be made from a particular file and when importing this one element, we don't have to worry about giving the same name to our import. This combination of export and import allows us to implement modularity.


1 Answers

No, it is impossible to make a getter for a module export - they are variable bindings, not properties.

However you could simply make that a default export:

export default __globalFluxStorage.state.property.property.property.property;

import DynamicModule from 'dynamic-module';

If you want a named import, you'll have to declare the name in your export:

export var DynamicModule = __globalFluxStorage.state.property.property.property.property;

import {DynamicModule} from 'dynamic-module';

This would also allow changing the value later when it's not available right at the time of the module being loaded:

export var DynamicModule;
…
DynamicModule = __globalFluxStorage.state.property.property.property.property;

(although in that case you might want to consider exporting a Promise or EventEmitter instead)

like image 98
Bergi Avatar answered Oct 19 '22 10:10

Bergi