Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6's export and curly braces

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.

like image 598
devwannabe Avatar asked Jan 08 '16 03:01

devwannabe


1 Answers

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.

like image 133
Esteban Avatar answered Oct 23 '22 12:10

Esteban