Default Exports and Imports
Besides named exports, ES6 modules also have default exports. Use a default export when a module has one main value to export. The module can still have named exports too.
Exporting a Default Value
Use export default to mark a value as the default export:
// account.js
const INTEREST_RATE = 0.2;
class Account {
constructor(balance = 0) {
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
this.balance -= amount;
}
}
export default Account;
export { INTEREST_RATE as interest };
In this example, Account is the default export, while interest is a named export.
Importing a Default Export
When importing a default export, you do not use curly braces:
// script.js
import Account from "./account.js";
const checking = new Account(100);
checking.deposit(20);
console.log(checking.balance); // 120
You can name the default import anything you want — it does not have to match the exported name.
Combining Default and Named Imports
You can import both default and named exports in a single statement:
// script.js
import Account, { interest } from "./account.js";
console.log(interest); // 0.2
const checking = new Account(100);
checking.deposit(20);
console.log(checking.balance); // 120
The default export comes first (without braces), followed by named exports in braces.
Alternative Syntax for Default Imports
You can also import the default export using the default keyword with an alias:
// script.js
import { default as CheckingAccount, interest } from "./account.js";
console.log(interest); // 0.2
const checking = new CheckingAccount(100);
checking.deposit(20);
console.log(checking.balance); // 120
This syntax is less common but can be useful when you want all imports in a consistent format.