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

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.

Leave a Reply