Sub topic 3
Default Exports and When to Use Them
This chapter assumes you know core JavaScript syntax, the difference between let, const, and var, and how named exports work from the previous chapter. You will learn how a default export is declared and what the engine actually creates for it. You will also learn which mistakes are common and how to decide between a default export and named exports.
What a Default Export Is
A default export is the one value a module offers as its main thing. An importer can take it without knowing any name inside the module and can call it whatever it likes.
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
// main.js
import greet from './greet.js';
console.log(greet('Ada')); // Hello, Ada!The import greet from line has no braces. That form asks for the default export, and the importer chooses the local name.
The default export is a named export called `default`
There is nothing magical in the module system here. Every module has a table of exported names. A default export is an entry in that table whose name is the string default. The import form without braces is shorthand for asking for that entry.
// main.js
import greet from './greet.js';
import { default as greet2 } from './greet.js';
import * as greeting from './greet.js';
console.log(greet === greet2); // true
console.log(greet === greeting.default); // trueBecause default is a reserved word, you can't write import { default } from .... You must rename it with as, which is why the brace-less shorthand exists. The import forms are covered in full in the next chapter.
The Syntax Forms
A module can have at most one default export. If you declare a second one, you get a SyntaxError before any code runs. The forms below are alternatives, so each belongs in its own file.
// format.js: named function declaration
export default function format(value) {
return String(value).trim();
}// anonymous.js: anonymous function declaration (allowed only with export default)
export default function (value) {
return value * 2;
}// cache.js: class declaration
export default class Cache {
#store = new Map();
get(key) { return this.#store.get(key); }
set(key, value) { this.#store.set(key, value); }
}// answer.js: any expression
export default 6 * 7;// alias.js: export list with renaming
function parse(text) {
return text.split(',');
}
export { parse as default };You can also put one default export and any number of named exports in the same module:
// logger.js
export default function log(message) {
console.log(`[app] ${message}`);
}
export const level = 'info';What you cannot write
| Attempt | Result | Why |
|---|---|---|
| `export default const x = 1;` | SyntaxError | `export default` takes an expression or a function/class declaration, not a variable declaration |
| `export default a, b;` | SyntaxError | Only one value; the comma operator is not allowed at that position |
| Two `export default` statements | SyntaxError | The name `default` would be exported twice |
| `export default` inside a function or `if` block | SyntaxError | Exports must be at the top level of the module |
To export a const as the default, declare it first and then export it: const x = 1; export default x;.
Gotcha: Expression Defaults Are Not Live
Imports are normally live bindings, which means the importer sees later changes to the exporting module's variable. A later chapter covers this in detail. Default exports have one exception that catches people out.
export default <expression> evaluates the expression once. It stores the result in a hidden binding that the module cannot reassign. Writing export default current exports the value current had at that moment, not the variable itself.
// value.js
let current = 'first';
export default current;
export function change() {
current = 'second';
}
// main.js
import value, { change } from './value.js';
change();
console.log(value); // 'first': the default holds the evaluated valueThe export-list form export { current as default } exports the binding itself, so it stays live:
// value-live.js
let current = 'first';
export { current as default };
export function change() {
current = 'second';
}
// main.js
import value, { change } from './value-live.js';
change();
console.log(value); // 'second'export default function name() {} and export default class Name {} also export a real binding (name or Name). Function declarations are hoisted, so an export default function is usable even before its module has finished evaluating. That matters in circular dependencies. export default () => {} and export default class {} are not hoisted that way.
Common Errors
Treating a default object as named exports
A frequent pattern is exporting an object of helpers as the default:
// utils.js
function slugify(text) {
return text.toLowerCase().replace(/\s+/g, '-');
}
function capitalize(text) {
return text[0].toUpperCase() + text.slice(1);
}
export default { slugify, capitalize };The import below fails during linking, before any code runs, with an error like "The requested module './utils.js' does not provide an export named 'slugify'":
import { slugify } from './utils.js'; // SyntaxErrorThe braces look like object destructuring, but they ask for export names. The module exports only default. The working version imports the object and then destructures it:
import utils from './utils.js';
const { slugify } = utils;
console.log(slugify('Hello World')); // hello-worldA better fix is to export slugify and capitalize by name. Bundlers can then drop whichever function you don't use. A single default object is one value, so it is kept or dropped as a whole.
Inconsistent local names
The importer picks the name, so one codebase can end up with import log from, import logger from, and import print from for the same function. Searching for usages becomes harder, and editor auto-import is less reliable. Named exports fix the name at the source, and every importer uses that name unless it renames explicitly with as.
Expecting `require()` to return the function
When CommonJS code loads an ES module, or a build tool converts one module format to the other, the default export often shows up as a .default property, not as the value itself. If you see TypeError: x is not a function, check whether you need x.default. The CommonJS chapter covers the exact rules.
When to Use a Default Export
Use the criteria below to decide.
| Situation | Prefer | Reason |
|---|---|---|
| The module exists to provide exactly one thing (a component, a class, a single function) | Default | The file name already names the thing, and importing it is short |
| A framework or tool requires it (for example, route or page files, config files that load a default) | Default | The loader looks up the `default` export by convention |
| The module offers several related utilities | Named | Each one is tree-shakable and has a stable name |
| You expect the API to grow | Named | Adding a second named export doesn't change how existing imports look |
| A barrel module will re-export it | Named | `export *` does **not** re-export `default`, so defaults need explicit `export { default as X } from` lines |
| A team wants consistent names across files | Named | Renaming becomes an explicit `as` that is easy to search for |
A reasonable default policy: use named exports everywhere, and add a default export only when a module has one clear main value or a tool requires it. Some teams enforce "named exports only" with a lint rule. That rule is also reasonable, apart from the framework conventions it has to exempt.
Exercise
A module contains let total = 0; export default total; export function add(n) { total += n; }. An importer runs import t, { add } from './m.js'; add(5); console.log(t);. What is logged, and what one-line change to the module makes it log 5?
Show answer
It logs 0, because export default total exports the value of the expression at evaluation time, not the binding. Replacing that line with export { total as default }; exports the live binding, so the importer sees 5.
Exercise
Which of these lines are valid in a module that has no other exports? (a) export default const limit = 10; (b) export default function () { return 1; } (c) const limit = 10; export { limit as default }; (d) export default 10, 20;
Show answer
Only (b) and (c). (a) is a SyntaxError because export default cannot take a variable declaration. (d) is a SyntaxError because only a single assignment expression may follow export default.
Exercise
shapes.js ends with export default { area, perimeter };. A teammate writes import { area } from './shapes.js'; and gets an error at load time. Explain the error and give the fix you would recommend.
Show answer
The braces request an export named area, but the module exports only default, so linking fails with a "does not provide an export named 'area'" SyntaxError. The recommended fix is to change shapes.js to export { area, perimeter }; (or put export on each declaration). That makes the import work and lets bundlers tree-shake unused functions.