Difference between 'export' and 'export default' in JavaScript?

JavascriptEcmascript 6

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser818700View Question on Stackoverflow
Solution 1 - JavascriptJesseView Answer on Stackoverflow
Solution 2 - JavascriptsanketView Answer on Stackoverflow