Named Export
Named Export is used when exporting multiple variables, functions, or classes from a module. Each exported element has a name, which allows you to selectively import only the parts you need.
For example, you can write code like this:
// utils.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
export class Calculator {
subtract(a, b) {
return a - b;
}
}When you export like this, you can import it in the place where you use it as follows:
// main.js
import { PI, add, Calculator } from './utils.js';
console.log(PI); // 3.14
console.log(add(2, 3)); // 5
const calc = new Calculator();
console.log(calc.subtract(5, 2)); // 3Default Export
Default Export is used when exporting a single default value from a module. You can have only one Default Export per module, and you can specify a name when importing it.
Export like this,
// logger.js
export default function log(message) {
console.log(message);
}And import like this:
// app.js
import log from './logger.js';
log('Hello!'); // Hello!Key Differences
- Export Count
- Named Export: Multiple allowed
- Default Export: Only one per module
- Import Syntax
- Named Export:
import { name1, name2 } from './module'; - Default Export:
import anyName from './module';
- Named Export:
- Renaming
- Named Export:
import { originalName as newName } from './module'; - Default Export: Can be freely named when importing
- Named Export:
- Bulk Import
- Named Export:
import * as moduleName from './module'; - Default Export: Not necessary as it's already treated as a single object
- Named Export:
- Dynamic Import
- Named Export:
import('./module').then(module => module.namedExport) - Default Export:
import('./module').then(module => module.default)
- Named Export:
When to use which?
- Named Export: Useful when you want to export multiple utility functions or variables and selectively import them for use.
- Default Export: Good for exporting the main functionality or class of a module.
Avoid Export Default
This document suggests avoiding the use of Export Default (at least in TypeScript projects). The main reasons are as follows:
No Support for Renaming
When renaming through refactoring features in an IDE, it doesn't change automatically. For example, even if you change the name of TestComponent to TestComponent2, it won't change in the import section. However, when using Named Export, it updates correctly.
Lack of Consistency due to Freedom of Renaming
- When using
default export, you can use any name when importing, which can lead to the same module being used with different names in different files. - This can break code consistency and cause confusion.
Lack of Type Information
default exportdoes not provide type information, so it may not be clear what type of object or function is being exported.