88

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'
Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155
sanchit
  • 1,538
  • 1
  • 16
  • 20

5 Answers5

148

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.

vsync
  • 87,559
  • 45
  • 247
  • 317
Michał Perłakowski
  • 70,955
  • 24
  • 137
  • 155
  • 19
    ```export { default as MyModule } from "./my-modue.js"; const { oneSmallFunction } = MyModule ``` Just going extra mile. – Alan Dong Oct 18 '18 at 21:48
  • 1
    @AlanDong your suggestions looks like a very valid solution to me. Why don't you post it as an answer ? – Danielo515 Nov 16 '18 at 08:31
16
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:

Community
  • 1
  • 1
vsync
  • 87,559
  • 45
  • 247
  • 317
15

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)

export { default } from './App'

// in a different file
import App from './index'

2. named export

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

// in another file
import { App } from './index'

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

Fernando Rojo
  • 908
  • 10
  • 12
0
import App from './App';
export default (App);

This work for me in default 'create-react-app' application

Andriy Viyatyk
  • 151
  • 1
  • 2
0

The only working solution is :

import App from './App';

export default App;

If you export your module like this

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

Then it's not a default export anymore and you'll get an error if you try to import it as a default import.

Melchia
  • 16,699
  • 16
  • 70
  • 93