Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"export default from" doesn't work with Babel React

I use react to build my library of components. I need to have an index.js to import all components in one place.

Something like this:

MyComponents/
  Button.js
  Label.js
  index.js

Inside the index.js I tried to do next:

// this export nothing
export {default} from './Button';
// this tells me about syntax error
export default from './Button';

I found only this solution that works

import Button from './Button';
export default Button;

But I found that some React Component libraries uses syntax that I mentioned above (export default from './Button') - and it works somehow. Looks like they use some babel-plugin-transform-* to do this.

Please find me to find how to transform my two lines of import export to one line of export ... from .... Thank you.

P.S. In the end I need to do this: import Button from './MyComponents';

like image 735
Anton Danilchenko Avatar asked Dec 07 '16 22:12

Anton Danilchenko


2 Answers

Use the following syntax:

File: layouts/index.js

export {default as Flex} from './flex'
export {default as Grid} from './grid'
export {default as Dock} from './dock'

Then you can use

import { Dock, Grid } from 'layouts'

or

import layouts from 'layouts'

<layouts.Flex >...</layouts.Flex>

In order to export nested indices created by the above method you can use export * syntax:

File: icons/index.js

export * as action from './action';
export * as alert from './alert';
export * as av from './av';

Usage:

import * as icons from 'material/icons'

<icons.action.Close />
like image 192
Przemysław Zalewski Avatar answered Sep 18 '22 13:09

Przemysław Zalewski


To use this construction:

export default from './Button';

we need to use preset-stage-1.

How to use

  1. npm install babel-preset-stage-1 --save-dev
  2. edit file package.json and add stage-1 to the presets section in babel.

Example of package.json

"babel": {
  "presets": [
    "es2015",
    "stage-1",
    "react"
  ]
},

More info

It's a proposal to the ECMAScript - https://github.com/leebyron/ecmascript-export-default-from (still in review).

like image 22
Anton Danilchenko Avatar answered Sep 18 '22 13:09

Anton Danilchenko