0

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?

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206

1 Answers1

2
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.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    No, that's not what happening here at all. It's just constructing an object of the shape `{"myConst": myConst, ...}` and exporting that. There is a single object exported with this syntax. – AKX Sep 08 '22 at 07:31
  • OK I figured out my confusion. It's because of name independence in exports. The default export is a constant, and when the default import is imported from the service, it's being imported (and therefore aliased) as `myConst`. That's confusing, as there's a constant within the service that's also called `myConst`, which isn't what's actually being referenced by `myConst` in the consumer. – Chris Halcrow Sep 08 '22 at 07:34
  • 2
    Yes, as an importer you're at liberty of choosing any name you like for the default value. `import quadVentiPumpkinSpiceLatte from 'service.js';` and `console.log(quadVentiPumpkinSpiceLatte.key1)` will work fine too. – AKX Sep 08 '22 at 07:35