default export vs named export in nodejs modules
In JavaScript, modules can export values using two primary styles: default exports and named exports. Understanding the difference between these two types of exports is essential for effectively using and creating modules.
Default Exports
Default exports allow a module to export a single value as the default export. This is useful when a module only needs to export one main thing, such as a class, function, or object.
Syntax
Exporting:
// module.js
const myFunction = () => { ... };
export default myFunction;
Importing:
// main.js
import myFunction from './module.js';
myFunction();
When you use a default export, you can give the imported value any name you want.
Example
// square.js
export default function square(x) {
return x * x;
}
// main.js
import square from './square.js';
console.log(square(5)); // 25
Named Exports
Named exports allow a module to export multiple values. These can be functions, classes, variables, etc. Named exports are useful when a module has multiple functionalities to export.
Syntax
Exporting:
// module.js
export const foo = () => { ... };
export const bar = () => { ... };
Importing:
// main.js
import { foo, bar } from './module.js';
foo();
bar();
With named exports, you must use the same names when importing as those used in the module.
Example
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
Combining Default and Named Exports
A module can use both default and named exports. This is useful if the module has a primary export (default) and some secondary exports (named).
Syntax
Exporting:
// module.js
const myFunction = () => { ... };
const foo = () => { ... };
const bar = () => { ... };
export default myFunction;
export { foo, bar };
Importing:
// main.js
import myFunction, { foo, bar } from './module.js';
myFunction();
foo();
bar();
Practical Example
Here’s a complete example combining default and named exports in a single module.
Exporting:
// utilities.js
const mainUtility = () => { ... };
const auxiliaryUtility1 = () => { ... };
const auxiliaryUtility2 = () => { ... };
export default mainUtility;
export { auxiliaryUtility1, auxiliaryUtility2 };
Importing:
// app.js
import mainUtility, { auxiliaryUtility1, auxiliaryUtility2 } from './utilities.js';
mainUtility();
auxiliaryUtility1();
auxiliaryUtility2();