What is "export default" in JavaScript?
Asked Answered
M

12

891

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?

Manama answered 14/1, 2014 at 15:21 Comment(4)
This is a very clear explanation on this 24ways.org/2014/javascript-modules-the-es6-wayPhyto
export keyword details here. Currently it is not supported natively by any of the web browsers.Nonalignment
It's now supported in all browsers but IE.Keratose
Very good answer https://mcmap.net/q/48966/-what-does-quot-export-default-quot-do-in-jsxCalyx
F
684

It's part of the ES6 module system, described here. There is a helpful example in that documentation, also:

If a module defines a default export:

// foo.js
export default function() { console.log("hello!") }

then you can import that default export by omitting the curly braces:

import foo from "foo";
foo(); // hello!

Update: As of June 2015, the module system is defined in §15.2 and the export syntax in particular is defined in §15.2.3 of the ECMAScript 2015 specification.

Folium answered 14/1, 2014 at 15:25 Comment(6)
@GeenHenk I suppose that's to be expected since ES6 is still a draft. I've provided an updated link and a disclaimer.Folium
I do not see how export default function(){} is any different from export = function(){}....Tartan
what about cases where it's like export const Foo = () => {} and then at end of file export default Foo I see this in a bunch of react examples. What's with the two exports?Rolle
It would be nice to see an example with default and named exports. In other words, such export which would satisfy import foo, { bar, baz } from './foo';Redcoat
Thanks for answering, but the usage of foo in the second example is a bit ambiguous; what's foo and how did you name the first file; how come you can do import foo from "foo"? Was there an object that held foo, since in the first example your exported function is unnamed. @FoliumUnderclothing
I agree with the comment of @nosahama. It is confusing because the second file could actually have been rewitten as js import garbage from "foo"; garbage(); and this would still produce the same result. I can only attribute this "feature" with an apparent belief among the JS designers that anonymous things are good if not great because they give you flexibility. I haven't found any acceptable explanation, even in MDN, for this keyword.Instanter
P
266

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
Psychiatrist answered 13/5, 2017 at 8:47 Comment(2)
import {cube} from ... vs import cube from ... ? It was simple already, what's the point then?Albuminate
So, are function names case-insensitive? You're importing Cube from 'cube' (the module), but you define the function inside cube.js as cube, not Cube.Borate
P
128

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.

Paprika answered 5/12, 2019 at 16:24 Comment(0)
B
109

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.

Blueprint answered 13/7, 2015 at 13:47 Comment(5)
You can use default and named exports together if you want to.Outnumber
@Greg gum the page is outdated. It is redirecting to exploringjs.com/es6/ch_modules.htmlTrengganu
@rajakvk, True, but the original page has a lot more background information for those getting started.Blueprint
This answer is better than accepted one because it explains what default mean and for me the question was about this word.Ringent
@DariuszSikorski the accepted answer explains what default means, being that the default export can be imported without using braces. This answer is actually pretty wrong as it says you can only use default when there is only one export in a file, which is not true at all. You can have several exports in the same file, but of course only 1 of them can be set as the default one.Kacerek
R
25

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
Ruhnke answered 28/10, 2018 at 17:42 Comment(1)
What if one decides to use the existing name myVar as any name for the default?Albuminate
M
16

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.
Malinger answered 4/6, 2020 at 12:17 Comment(0)
P
14

One of the good features introduced in ES6 was javascript modules in an efficient way by which we can export and import variables, functions, and classes between different .js files.

We have two different ways to export: Named exports and Default exports. To properly understand the default export, we must first understand the named export well.

Named export

In this case, in the source file, we export the desired variables, functions, or classes that have a specific name. The syntax is as follows:

// file: source.js
export const myVariable = /* … */
export function myFunction() { /* … */ }
export class myClass { /* … */ }

Now, to access the above items in the target file, we must import them as follows:

// file: target.js (in the same directory as the source.js file) 
import { myVariable } from "./source.js"
import { myFunction } from "./source.js"
import { myClass } from "./source.js"

Now it's time to get to the main question "what exactly is the default export"?

Default export

Except for the cases where we exported them by name (named exports), there is a similar feature called default export that can be used only once in each .js file. See the following example and compare it with the previous source.js file:

// file: source.js
export default function myNewFunction() { /* … */ }
export const myVariable = /* … */
export function myFunction() { /* … */ }
export class myClass { /* … */ }

In fact, each .js file can have "multiple named exports" and "only one default export"_ here myNewFunction is exported as default. With this, when importing in the target file, javascript understands which item is exported as default.

The item that is "exported as default" (myNewFunction) is imported in the target.js file as follows:

// file: target.js (in the same directory as the source.js file)
import anyName from "./source.js"

Look carefully at the differences! Here, we don't have { } sign after import, and we used a custom name that we didn't have in the source file. Here anyName represents myNewFunction.

This shows that we can give "any desired name" to the item that is "exported as default" when importing it and just pointing to the "path" of the source file, JavaScript will find that file and import it.

Some important notes:

  • Unlike named exports, in default export we don't need to export named items and we can export "unnamed" items as well.

  • Why did they add the Default export feature to ES6 at all!? for the ability to export "unnamed items" (anonymous functions and classes) as well as expressions and even object literals in addition to named items.

Possing answered 23/11, 2022 at 12:4 Comment(0)
C
13

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:

export default function foo(){}

it can be imported in bar.js using:

import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
Comate answered 9/10, 2019 at 6:30 Comment(0)
H
7

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

Houser answered 6/2, 2021 at 19:43 Comment(0)
C
6

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';
Criner answered 7/3, 2023 at 3:30 Comment(0)
N
2

In ES6 there are two kinds of exports:

Named exports - for example export function func() {} is a named export with the name of func. Named modules can be imported using import { exportName } from 'module';. In this case, the name of the import should be the same as the name of the export. To import the func in the example, you'll have to use import { func } from 'module';. There can be multiple named exports in one module.

Default export - is the value that will be imported from the module, if you use the simple import statement import X from 'module'. X is the name that will be given locally to the variable assigned to contain the value, and it doesn't have to be named like the origin export. There can be only one default export.

A module can contain both named exports and a default export, and they can be imported together using import defaultExport, { namedExport1, namedExport3, etc... } from 'module';.

Neile answered 10/8, 2022 at 19:23 Comment(0)
S
-4

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

Substantialize answered 23/12, 2019 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.