Re-exporting ES6 modules

Still need a little help getting ES6 compiling smoothly? First find out how.

With the advent of Babel, ES6 modules have become a real option for organising code. Mapping your require statements to import and module.exports to export is intuitive and will get you up and running, but the syntax for doing anything else can be downright unexpected.

I ran into this today while translating index.coffee from numbat-ui to ES6. index.coffee follows a fairly common pattern for libraries – instead of defining anything interesting itself, it just re-exports the classes from component modules for consumption by the app using the library. Basically, doing this:

module.exports = {
  AppBar: require('./components/AppBar/AppBar'),
  AppCanvas: require('./components/AppCanvas/AppCanvas'),
  // ...
}

Given ES6’s import isn’t an expression which returns an object, the naive way of accomplishing this would be something like:

import AppBar from './components/AppBar/AppBar';
import AppCanvas from './components/AppCanvas/AppCanvas';
// ...

export AppBar, AppCanvas; //, ...

But Babel doesn’t even compile this.

Edit: as Tim Branyen mentioned below, this does work, just add braces: export {AppBar, AppCanvas}.

A little reading at 2ality explained that you can re-export everything:

export * from 'components/AppBar';

Or pick, choose and rename:

export { Lists as List, ListItem } from 'components/Lists/Lists';

But this still feels incorrect – it will allow us to re-export component modules, but not if the components use export default.

It turns out though, that you can re-export the default module. How? By renaming default:

export { default as myFoo } from 'src/other_module';

Intuitive? Not really. But does it work? Sure does. With this syntax, this is how we’d end up translating the first example:

export { default as AppBar } from './components/AppBar/AppBar';
export { default as AppCanvas } from './components/AppCanvas/AppCanvas';

If you want to make Single Page Apps which people love and value your time, subscribe to my newsletter!

In return for your e-mail, you’ll also immediately receive 3 bonus print-optimised PDF cheatsheets – on ES6, React and JavaScript promises.

I will send you useful articles, cheatsheets and code.

I won't send you useless inbox filler. No spam, ever.
Unsubscribe at any time.

4 Comments Re-exporting ES6 modules

  1. Tim Branyen

    I recently tried the:

    > export AppBar, AppCanvas; //, …
    But Babel doesn’t even compile this.

    feature and realized that it does work, you just forgot to add the surrounding { … }. It should look something like:

    export { AppBar, AppCanvas };

    Reply

Leave a Reply

Your email address will not be published.