79

What exactly is the difference between the two? I've seen people use:

function foo () {
  ...
}

export default foo;

And I've seen:

function bar () {
  ...
}

export bar;

Also, why would you use the one over the other?

Ouroborus
  • 16,237
  • 4
  • 39
  • 62

2 Answers2

158

It's easiest to just look at what the three different ES6 import/export styles compile down to in CommonJS.

// Three different export styles
export foo;
export default foo;
export = foo;

// The three matching import styles
import {foo} from 'blah';
import foo from 'blah';
import * as foo from 'blah';

Roughly compiles to:

exports.foo = foo;
exports['default'] = foo;
module.exports = foo;

var foo = require('blah').foo;
var foo = require('blah')['default'];
var foo = require('blah');

(Actual compiler output may differ)

Jesse
  • 6,725
  • 5
  • 40
  • 45
33

If your need is to export multiple objects go with named exports(without default keyword).

function x1(){};
function x2(){};
export {x1},{x2};  //my-module.js
import {x1},{x2} from 'my-module';

otherwise for a single export, default export works well

export default function x1() {};
import x1 from 'my-module';
sanket
  • 664
  • 6
  • 16
  • 6
    it doesn't have anything to do with the `default` keyword – ieXcept Aug 19 '17 at 08:04
  • 5
    Agreed with @ieXcept. the `default` keyword has nothing to do with multiple exports. It is named vs unnamed exports. –  Oct 29 '17 at 01:57
  • 4
    Default is technically still a named export. It’s exported under `default` name. – demisx Feb 22 '18 at 15:48