Difference between 'export' and 'export default' in JavaScript? [duplicate]

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?


Solution 1:

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)

Solution 2:

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';