ES6 nested imports (Babel+react)

With the ES 6 module system, you have a choice of whether to use a single default export:

export default DefaultObject

or potentially many named exports:

export const NondefaultObject = {}

You import these slightly differently, but otherwise they work the same:

import DefaultObject from './DefaultObject'
import {NondefaultObject} from './NondefaultObject'

const App = () => (
  <div>
    <DefaultObject/> 
    <NondefaultObject />
   </div>
)

Where things go awry is where you want to aggregate up imports, as per Jack Hsu’s excellent article on Redux application structure.

import * as do from './DefaultObject'
import * as ndo from './NondefaultObject'

const App = () => (
  <div>
    <do.DefaultObject/>       // Does NOT work
    <ndo.NondefaultObject />  // works
    <do.default/>              // works
   </div>
)

Why is it so? When you import a default export, the name of the object is actually “default”. Somewhere in the Babel/Redux/React magic factory, somebody is clever enough to use the module name as an alias for its own default export when you use that module name in a JSX tag. However, when you assign that same default export to another value and then try to use that value (as in the import * case), no such magic occurs.

Leave a Reply

Your email address will not be published. Required fields are marked *