Javascript 使用 ES6/2015 导出对象文字的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34619640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to export an object literal with ES6/2015?
提问by Svitlana
Seemingly a very simple task...
看似很简单的任务...
export default function() {
return {
googleClientID:'xxxx'
}
}
Is it the best way to export object literal with app settings?
这是使用应用程序设置导出对象文字的最佳方式吗?
回答by madox2
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.
不同之处在于,在您的情况下,每次调用导出的函数时都会获得全新的对象。在这种情况下,您每次都会得到相同的对象。取决于你需要什么。
回答by void
You can simply export a object
您可以简单地导出一个对象
export default { googleClientID:'xxxx' };
or even
甚至
export default foo = { googleClientID:'xxxx' };
A default exportcan 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.
一个默认的出口可以是函数,类,对象或其他任何东西。该值将被视为“主要”导出值,因为它是最容易导入的。
回答by e-cloud
@madox2 's and @void 's answer may be some kind of common misunderstanding.
@madox2 和 @void 的回答可能是某种常见的误解。
I just ran into a similar problem while issuing a PR to DefinitelyTyped-- #18725. The typescript compiler complains about the generated files.
我刚刚在向绝对类型的 PR 发出 PR 时遇到了类似的问题- #18725。打字稿编译器抱怨生成的文件。
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.
乍一看,我不认为这是我的问题。因为我只是从lodash-es
. 但是后来我找不到任何简单的方法来消除错误。
So I go to the specfor 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:
刚刚找到更多参考资料: