ES6 Nested Imports (Babel + React)
Here's a quick tip on using the proper module imports in JavaScript ES6 for Babel and ReactJS
Join the DZone community and get the full member experience.
Join For FreeWith 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.
Published at DZone with permission of Jaime Metcher, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments