Lesson 73 - Mixing Named and Default Exports in JavaScript
JavaScript modules allow you to use both named and default exports in the same file. This gives you the flexibility to expose one primary functionality (default export) and additional utilities (named exports) from the same module.
Recap: Export Types
- Default export ? The main export from a file (no curly braces needed on import).
- Named exports ? You can have multiple named exports (imported with curly braces).
Mixing Both: Example
// utils.js
export default function greet(name) {
return `Hello, ${name}!`;
}
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
Importing Both Together
You can import the default and named exports at the same time:
// main.js
import greet, { add, PI } from './utils.js';
console.log(greet("Lance")); // Hello, Lance!
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
Notes
- The default export can be renamed to anything you like.
- Named exports must be imported using the exact names (or renamed using
as
). - You can skip importing the default or named exports if you don’t need them.
Common Mistakes
// Wrong: Trying to import default as named
import { greet } from './utils.js'; // Error if greet is default
// Correct
import greet from './utils.js';
Try Your Hand
-
Create a
mathUtils.js
file:- Default export a
calculateArea(radius)
function. - Named export constants:
PI = 3.14
,E = 2.718
.
- Default export a
-
Import everything in a
main.js
file and use them to compute and log results.
Self - Quiz
- Can you have both named and default exports in the same file?
- Do you need curly braces to import the default export?
- What’s the benefit of mixing export types in one module?