[javascript] What is "export default" in JavaScript?

File: SafeString.js

// Build out our basic SafeString type
function SafeString(string) {
  this.string = string;
}

SafeString.prototype.toString = function() {
  return "" + this.string;
};

export default SafeString;

I have never seen export default before. Are there any equivalent stuff for export default that can be easier to understand?

This question is related to javascript node.js ecmascript-6

The answer is


export default is used to export a single class, function or primitive.

export default function() { } can be used when the function has no name. There can only be one default export in a file.

Read more


There are two different types of export, named and default. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above. Source: MDN

Named Export

export class NamedExport1 { }

export class NamedExport2 { }

// Import class
import { NamedExport1 } from 'path-to-file'
import { NamedExport2 } from 'path-to-file'

// OR you can import all at once
import * as namedExports from 'path-to-file'

Default Export

export default class DefaultExport1 { }

// Import class
import DefaultExport1 from 'path-to-file' // No curly braces - {}

// You can use a different name for the default import

import Foo from 'path-to-file' // This will assign any default export to Foo.

export default function(){} can be used when the function doesn't have a name. There can only be one default export in a file. The alternative is a named export.

This page describes export default in detail as well as other details about modules that I found very helpful.


export default is used to export a single class, function or primitive from a script file.

The export can also be written as

export default function SafeString(string) {
  this.string = string;
}

SafeString.prototype.toString = function() {
  return "" + this.string;
};

This is used to import this function in another script file

Say in app.js, you can

import SafeString from './handlebars/safe-string';

A little about export

As the name says, it's used to export functions, objects, classes or expressions from script files or modules

Utiliites.js

export function cube(x) {
  return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;

This can be imported and used as

App.js

import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

Or

import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo);    // 4.555806215962888

When export default is used, this is much simpler. Script files just exports one thing. cube.js

export default function cube(x) {
  return x * x * x;
};

and used as App.js

import Cube from 'cube';
console.log(Cube(3)); // 27

As explained on this MDN page

There are two different types of export, named and default. You can have multiple named exports per module but only one default export[...]Named exports are useful to export several values. During the import, it is mandatory to use the same name of the corresponding object.But a default export can be imported with any name

For example:

let myVar; export default myVar = 123; // in file my-module.js

import myExportedVar from './my-module' //  we have the freedom to use 'import myExportedVar' instead of 'import myVar' because myVar was defined as default export

console.log(myExportedVar);        // will log 123

Export Default is used to export only one value from a file which can be a class, function, or object. The default export can be imported with any name.

//file functions.js

export default function subtract(x, y) {
  return x - y;
}

//importing subtract in another file in the same directory
import myDefault from "./functions.js";

The subtract function can be referred to as myDefault in the imported file.

Export Default also creates a fallback value which means that if you try to import a function, class, or object which is not present in named exports. The fallback value given by default export will be provided.

A detailed explanation can be found on https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export


In my opinion, the important thing about the default export is that it can be imported with any name!

If there is a file, foo.js, which exports default:

_x000D_
_x000D_
export default function foo(){}
_x000D_
_x000D_
_x000D_

it can be imported in bar.js using:

_x000D_
_x000D_
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
_x000D_
_x000D_


What is “export default” in JavaScript?

In default export the naming of import is completely independent and we can use any name we like.

I will illustrate this line with a simple example.

Let’s say we have three modules and an index.html file:

  • modul.js
  • modul2.js
  • modul3.js
  • index.html

File modul.js

export function hello() {
    console.log("Modul: Saying hello!");
}

export let variable = 123;

File modul2.js

export function hello2() {
    console.log("Module2: Saying hello for the second time!");
}

export let variable2 = 456;

modul3.js

export default function hello3() {
    console.log("Module3: Saying hello for the third time!");
}

File index.html

<script type="module">
import * as mod from './modul.js';
import {hello2, variable2} from './modul2.js';
import blabla from './modul3.js'; // ! Here is the important stuff - we name the variable for the module as we like

mod.hello();
console.log("Module: " + mod.variable);

hello2();
console.log("Module2: " + variable2);

blabla();
</script>

The output is:

modul.js:2:10   -> Modul: Saying hello!
index.html:7:9  -> Module: 123
modul2.js:2:10  -> Module2: Saying hello for the second time!
index.html:10:9 -> Module2: 456
modul3.js:2:10  -> Module3: Saying hello for the third time!

So the longer explanation is:

'export default' is used if you want to export a single thing for a module.

So the thing that is important is "import blabla from './modul3.js'" - we could say instead:

"import pamelanderson from './modul3.js" and then pamelanderson();. This will work just fine when we use 'export default' and basically this is it - it allows us to name it whatever we like when it is default.


P.S.: If you want to test the example - create the files first, and then allow CORS in the browser -> if you are using Firefox type in the URL of the browser: about:config -> Search for "privacy.file_unique_origin" -> change it to "false" -> open index.html -> press F12 to open the console and see the output -> Enjoy and don't forget to return the CORS settings to default.

P.S.2: Sorry for the silly variable naming

More information is in link2medium and link2mdn.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to ecmascript-6

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 where is create-react-app webpack config and files? Can (a== 1 && a ==2 && a==3) ever evaluate to true? How do I fix "Expected to return a value at the end of arrow function" warning? Enums in Javascript with ES6 Home does not contain an export named Home How to scroll to an element? How to update nested state properties in React eslint: error Parsing error: The keyword 'const' is reserved Node.js ES6 classes with require