Default Exports
In this page:
Creating a Default Export
Use export default to mark one declaration as a module's default export, signaling that this is the single main thing the file is meant to provide to other code.
Example: Creating a Default Export
// logger.ts
export default function log(message: string) {
console.log("[LOG]", message);
}
log("Hello from default export");
Importing a Default Export
A default export is imported without curly braces, and unlike a named import, the importer is free to choose any local name they like for it. This flexibility is convenient, but it also means the imported name gives no automatic hint about what the module actually calls it internally.
Example: Importing a Default Export
// logger.ts
export default function log(message: string) {
console.log("[LOG]", message);
}
// main.ts
// import myLogger from "./logger";
const myLogger = log;
myLogger("Custom name works fine");
Default and Named Exports Together
A module can have one default export and any number of named exports side by side, combining a primary export with supporting helpers exported under their own names.
Example: Default and Named Exports Together
// api.ts
export default function fetchData() {
return "data";
}
export const API_VERSION = "v2";
console.log(fetchData(), API_VERSION);
Default Exporting Expressions
A default export can also directly export an expression, such as an object literal or an anonymous function value, rather than requiring a previously-named declaration.
Example: Default Exporting Expressions
// config.ts
export default {
host: "localhost",
port: 8080,
};
const config = { host: "localhost", port: 8080 };
console.log(config);
When to Use Default Exports
Default exports are convenient when a module has one clear main concept — such as a single component, class, or configuration object — that the whole file exists to provide.
Example: When to Use Default Exports
// Button.ts
export default class Button {
constructor(public label: string) {}
}
const btn = new Button("Submit");
console.log(btn.label);
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: