Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When default exporting a constant, how is it possible to reference a collection within the constant using the name of another value in the constant?

I’m working on some existing code that exports a collection of key/value pairs by using a spread operation in the default export of a service like this:

keyValuePairs

{
  key1: func1,
  key2: func2
}

service.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const myConst = {
   //stuff here
};

export default {
  myConst,
  ...keyValuePairs,
};

consumer.js

import myConst from 'service.js';

// invoke delegate function by referencing its key in collection
myConst.key1

How am I able to reference key1 in the consumer as myConst.key1, when myConst is the name of a constant that’s included in the export?

>Solution :

export default {
  myConst,
  ...keyValuePairs,
};

is simply equivalent (aside from there being no someAnonymousThing in the module’s namespace) to

const someAnonymousThing = {
  myConst,
  ...keyValuePairs,
};
export default someAnonymousThing;

so it’s not a special pattern of exporting at all; just a regular object being exported as the default object of that module.

If the ... spread operator is new, then see the docs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading