Export multiple classes in ES6 modules

ambient picture ambient · Jul 13, 2016 · Viewed 146.9k times · Source

I'm trying to create a module that exports multiple ES6 classes. Let's say I have the following directory structure:

my/
└── module/
    ├── Foo.js
    ├── Bar.js
    └── index.js

Foo.js and Bar.js each export a default ES6 class:

// Foo.js
export default class Foo {
  // class definition
}

// Bar.js
export default class Bar {
  // class definition
}

I currently have my index.js set up like this:

import Foo from './Foo';
import Bar from './Bar';

export default {
  Foo,
  Bar,
}

However, I am unable to import. I want to be able to do this, but the classes aren't found:

import {Foo, Bar} from 'my/module';

What is the correct way to export multiple classes in an ES6 module?

Answer

webdeb picture webdeb · Jul 13, 2016

Try this in your code:

import Foo from './Foo';
import Bar from './Bar';

// without default
export {
  Foo,
  Bar,
}

Btw, you can also do it this way:

// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'

// and import somewhere..
import Baz, { Foo, Bar } from './bundle'

Using export

export const MyFunction = () => {}
export const MyFunction2 = () => {}

const Var = 1;
const Var2 = 2;

export {
   Var,
   Var2,
}


// Then import it this way
import {
  MyFunction,
  MyFunction2,
  Var,
  Var2,
} from './foo-bar-baz';

The difference with export default is that you can export something, and apply the name where you import it:

// export default
export default class UserClass {
  constructor() {}
};

// import it
import User from './user'