ES6's export and curly braces

℡╲_俬逩灬. 提交于 2020-08-22 05:34:05

问题


I saw a code got posted in a chat channel. At the very end of his code is

export {UserInformation};

There were groups saying that the syntax is wrong. Some were saying it is fine as long as the variable exists.

So which group is right? It's my first time seeing this kind of syntax too. I've never seen curly braces in export. I've only used them in import. Like this

import {method} from 'someModule';

If I was writing it, I would write it as

export default UserInformation;

I don't want to pollute my brain with wrong information. Let me know which export is correct.


回答1:


The syntax is correct. This

export {UserInformation};

is shorthand for

export {UserInformation as UserInformation};

which is like doing

export const UserInformation = {};

when you define UserInformation.

It's useful to be able to export something from a module in a different place where it's defined (for readability, for instance).

In this case, you'd import UserInformation like this

import {UserInformation} from 'UserInformation.js';

Please note that export default UserInformation; is not equivalent to this. In that case, you're making UserInformation be the default module export. To import UserInformation in that case, you'd do:

import UserInformation from 'UserInformation.js';

which is shorthand for

import {default as UserInformation} from 'UserInformation.js';

This blog post is an excellent read about the topic.



来源:https://stackoverflow.com/questions/34668861/es6s-export-and-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!