Svitlana
Svitlana

Reputation: 2374

What is the best way to export an object literal with ES6/2015?

Seemingly a very simple task...

export default function() {
    return {
        googleClientID:'xxxx'
    }
}

Is it the best way to export object literal with app settings?

Upvotes: 52

Views: 62335

Answers (4)

angelito
angelito

Reputation: 451

Exporting: not nicest, but handy when importing later.

export const ROOT = '/tmp/test'
export const EXT = '.backup'
// ... and so on

Importing: cleanest usage (and we usually import more than export).

import { ROOT, EXT } from './literals.js'
const file = ROOT + yourFileName + EXT

Upvotes: 1

void
void

Reputation: 36703

You can simply export an object

export default { googleClientID:'xxxx' };

A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.

Upvotes: 13

e-cloud
e-cloud

Reputation: 4471

@madox2 's and @void 's answer may be some kind of common misunderstanding.

I just ran into a similar problem while issuing a PR to DefinitelyTyped -- #18725. The typescript compiler complains about the generated files.

A example should be:

// ...
import zip from "./zip";
import zipObject from "./zipObject";
import zipObjectDeep from "./zipObjectDeep";
import zipWith from "./zipWith";

export default {
  // ...
  zip,
  zipObject,
  zipObjectDeep,
  zipWith
};

At the first glance, i didn't think its my problem. Because i just copy the code from lodash-es. But then i can't find any simple approach to remove the errors.

So I go to the spec for answer. Wow, the spec doesn't talk about default export of an object, if I read it right.

Conclusion:

The follow is spec-respected:

export { googleClientID:'xxxx' }

Just found some more references:

Upvotes: 2

madox2
madox2

Reputation: 51841

You can export object itself:

export default {
    googleClientID:'xxxx'
};

The difference is that in your case you will get brand new object every time you call exported function. In this case you will get the same object every time. Depends on what you need.

Upvotes: 98

Related Questions