Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-export default in ES 6 modules

In ES6, is it possible to shorten the following code. I have an App.js file and an index.js.

index.js

import App from './App';

export default App;

Something like this

index.js

export default App from './App.js'
like image 483
sanchit Avatar asked Oct 12 '16 13:10

sanchit


3 Answers

If you use proposal-export-default-from Babel plugin (which is a part of stage-1 preset), you'll be able to re-export default using the following code:

export default from "./App.js"

For more information see the ECMAScript proposal.


Another way (without this plugin) is:

export { default as App } from "./App.js"

The above is a very common practice when separate files, each with its own export, have all something in common, for example, utils, so if, for example, one would want to import 3 utility functions, instead of having to write multiple imports:

import util_a from 'utils/util_a' 
import util_b from 'utils/util_b' 
import util_c from 'utils/util_c' 

One could import any of the utilities in a single-line:

import { util_a, util_b , util_c } from 'utils' 

By creating an index.js file in the /utils folder and import all the defaults of all the utilities there and re-export, so the index file will serve as the "gateway" for all imports related to that folder.

like image 175
Michał Perłakowski Avatar answered Nov 19 '22 09:11

Michał Perłakowski


This is a bit of repetition from the previous answers, but to clarify the difference in two options:

1. Default export

(This appears to be what OP wants)

// index.ts
export { default } from './App'

Then, in a different file:

import App from './index'

2. Named export

export { default as App } from './App'

Then, in another file:

import { App } from './index'

Bonus: named → default export

If ./App uses a named export, but you want to re-export it as a default export, you can do that too:

export { App as default } from './App'

Then, in another file:

import App from './index'

These will work with react as vsync's answer states.

Bonus #2: export everything

Say you have a file that exports multiple items:

// App.ts
export const first = 1

export const second = 2

const final = 3

export default final

You can then re-export them directly:

// index.ts
export * from './App'

You can now import these easily:

import final, { first, second } from './index'

Bonus #3: * import

You can import all variables exported by another file as a single variable.

// index.ts
import * as App from './App'

App.first === 1 // true
like image 63
Fernando Rojo Avatar answered Nov 19 '22 11:11

Fernando Rojo


import App from './App';

export default App;

Babel 7 (with @babel/preset-react) can transform the below:

export { default as App } from './App.js';

Related discussions:

  • TC39 proposal: https://github.com/tc39/proposal-export-default-from#common-concerns
like image 17
vsync Avatar answered Nov 19 '22 10:11

vsync