Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export imported object in ES6?

The use case is simple: I just want to export an object with the name just as it was imported.

for example:

import React from 'react'; export React; 

but this does not work. I have to write:

import React from 'react'; export const React = React; 

But this is odd. What is the right way to do this?

UPDATED:

Thanks for helps and references. I have solved out my problem with many clues. I'd like to share some common cases for me and the solutions.

export imports

import d, {obj} from '...';  export {obj, d}; export {obj as name1, d as name2}; 

re-export all named imports

export * from '...'; export * as name1 from '...'; 

re-export some named imports

export {a, b as name1} from '...'; 

re-export default import as default export

export {default} from '...'; 

re-export default import as named export

export {default as name1} from '...'; 
like image 480
Yao Zhao Avatar asked May 13 '16 02:05

Yao Zhao


People also ask

Does ES6 import export?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

How do I export an object?

In Object Designer, select the object type that you want to export, or select All if you want to export different types of objects to the same file. Select one or more objects that you want to export. To select multiple objects, hold down the Ctrl key when you select objects. On the File menu, choose Export.

Can you export an object JavaScript?

The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import.


1 Answers

I often do the following in index.js files that compose several files:

export {default as SomeClass} from './SomeClass'; export {someFunction} from './utils'; export {default as React} from 'react'; 

This blog entry provides some nice additional examples.

Important note

You should be aware this eslint-rule when accessing these exported imports. Basically, in another file, you shouldn't:

import SomeClassModule from 'SomeClass/index.js'; SomeClassModule.someFunction(); // Oops, error 

You should do this:

import SomeClassModule, {someFunction} from 'SomeClass/index.js'; someFunction(); // Ok 
like image 136
Eric H. Avatar answered Sep 25 '22 14:09

Eric H.