Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ES6 Nested Imports (Babel + React)

DZone's Guide to

ES6 Nested Imports (Babel + React)

Here's a quick tip on using the proper module imports in JavaScript ES6 for Babel and ReactJS

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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 when you want to aggregate 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.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:
es-6 ,javascript ,front-end ,web development ,react js

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}