December 08, 2024 / 3 min read
Understanding export, export default, and module.exports in JavaScript
JavaScript
⚓︎Introduction
The differences between export default, Named Exports, and module.exports relate to how they are used to export and import modules in JavaScript.
⚓︎export default
- Used in ES6 modules (import/export syntax).
- Allows exporting a single default export from a module.
- The importing file can give it any name.
Example
export default function add(a, b) {
return a + b;
}import add from "./math.js"; // You can name it anything
console.log(add(2, 3)); // Output: 5⚓︎export (Named Exports)
- Allows exporting multiple named items from a module.
- The importing file must use the same names (or alias them) when importing.
Example
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}import { add, subtract } from "./math.js";
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 3)); // Output: 2
// You can also alias the imports:
import { add as sum } from "./math.js";
console.log(sum(2, 3)); // Output: 5⚓︎module.exports
- Used in CommonJS modules, which is the default module system in Node.js.
- Allows exporting values (objects, functions, primitives) from a module.
- Use require() to import these modules.
Example
module.exports = function add(a, b) {
return a + b;
};
// or
function add(a, b) {
return a + b;
}
module.exports = add;const add = require("./math.js");
console.log(add(2, 3)); // Output: 5⚓︎Mixed Exports with module.exports
You can also export multiple values as properties of an object.
Example
module.exports = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
},
};const math = require("./math.js");
console.log(math.add(2, 3)); // Output: 5
console.log(math.subtract(5, 3)); // Output: 2⚓︎Conclusion
Understanding the differences between export default, Named Exports, and module.exports is essential when working with JavaScript modules.
- Use export default when you want to export a single entity, and its name doesn't matter in the importing file.
- Choose Named Exports when you need to export multiple entities and ensure clarity by using explicit names.
- Use module.exports for Node.js projects or when working with CommonJS modules.
By mastering these export methods, you can create modular, maintainable, and reusable code for both frontend and backend applications.
Happy coding! 🚀
