Skip to main content
0 reactions

How to Use export default in JavaScript

A card titled export default, labelled JavaScript Basics, showing export default greet, an import of greet and the call greet(“Sam”) printing Hello, Sam!
export default: Share a file’s main value and import it by any name.

A JavaScript module can have one default export, its main value. export default marks it, and another file imports it without curly braces, under any name it likes.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
export default value;

import name from "./file.js";
  • export default value: makes value, such as a function, the file’s default export. A file can have only one.
  • import name from "./file.js": imports that default export from another file. name is any name you choose, written without curly braces.
  • "./file.js": the path to the file, starting with ./ for the same folder.

See export (opens in a new tab) and import (opens in a new tab) on MDN.

Prerequisites

The Example

Two files in the same folder: greet.js exports a greeting function as its default, and app.js imports it and calls it.

Step 1: Export the Function

greet.jsJavaScript
export default function greet(name) {
  return "Hello, " + name + "!";
}

export default in front of the function makes it the file’s main value.

Step 2: Import It

app.jsJavaScript
import greet from "./greet.js";

console.log(greet("Sam"));

The import has no curly braces, and the name greet is chosen here.

Step 3: Run It

TerminalBash
node app.js
OutputPlain text
Hello, Sam!

app.js called the function it imported from greet.js.

Common Mistakes

MistakeWhat happensDo this instead
Importing a default export with curly braces: import { greet }SyntaxError: The requested module './greet.js' does not provide an export named 'greet'Import it without braces: import greet from "./greet.js"
Writing export default twice in one fileSyntaxError: Identifier '.default' has already been declaredKeep one default export, and use named exports for the rest

Troubleshooting

ProblemCauseFix
A warning that mentions MODULE_TYPELESS_PACKAGE_JSONThe folder has a package.json without a "type" fieldAdd "type": "module" to it, as the warning says
SyntaxError: Cannot use import statement outside a moduleThe package.json says "type": "commonjs"Change it to "type": "module"

FAQ

Can a file have a default export and named exports?

Yes. Import both in one line: the default first, then the named ones in curly braces.

Conclusion

export default marks a file’s one main value, and import name from brings it in, without braces and under any name.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments