Notice: Normally I use webpack with babel to bundle all that stuff together and let ES6 modules work in older browsers, but for the sake of simplicity we can that step and just use a modern browser.

Default Exports

We'll start by building a pretty small module first, export it and then import it to use it in our main.js file.

// MyModule.js
const CoolFunction = name => console.log(`Hey ${name}, you are pretty cool!`);

export default CoolFunction;

So, now we got an really impressive module that default exports the CoolFunction to greet somebody and tell him, that he or she is pretty cool. Useful, right? Now let's use it!

// main.js
import CoolFunction from './MyModule.js';

CoolFunction('Matti');
// Result => "Hey Matti, you are pretty cool!"

So, the default export is designed to let you export a single object as default. This object can be a function, a class, an object or anything else.

One benefit of using the default export is that you can name the imported object as you want. For example this works too!

// main.js
import PrettyCoolFunction from './MyModule.js';

PrettyCoolFunction('Matti');
// Result => "Hey Matti, you are pretty cool!"

Named exports

A second way to export and import modules are named exports. Let's refactor our main and module code just a little bit.

// MyModule.js
export const CoolFunction = name => console.log(`Hey ${name}, you are pretty cool!`);
// main.js
import { CoolFunction } from './MyModule.js';

CoolFunction('Matti');
// Result => "Hey Matti, you are pretty cool!"

This works almost the same as the default export, except that the import is done via object destructuring and we directly export it.

The downside of that approach is that you can't rename your imported object like the default object.

// main.js
import { PrettyCoolFunction } from './MyModule.js';

PrettyCoolFunction('Matti');
// Result in webpack => "export 'PrettyCoolFunction' was not found in './MyModule.js'"

Mixing named and default

So let's try to mix named and default exports.

// MyModule.js
const CoolFunction = name => console.log(`Hey ${name}, you are pretty cool!`);

export const SadFunction = name => console.log(`Hey ${name}, I heard you're sad? WHat happened?`);

export default CoolFunction;
import PrettyCoolFunction, { SadFunction } from './MyModule.js';

PrettyCoolFunction('Matti');
SadFunction('Matti');
// Result => "Hey Matti, you are pretty cool!"
// Result => "Hey Matti, I heard you're sad? WHat happened?"

As you see, it's no problem to mix em. We also renamed the default export while importing it.

Here are some resources to learn more about ES6 module imports and export: