Accessing Default Exports
You'll learn how to retrieve a default export from a dynamically imported module's namespace object.
When you use dynamic import with a module that has a default export, the promise resolves to a module namespace object. This object isn't the default export itself—it's a container that holds all the module's exports, including the default one.
The .default Property
The default export lives on a special property called .default on the namespace object. To access it, you need to explicitly reference this property:
// Assuming 'utils.js' has: export default function add(a, b) { return a + b; }
async function loadUtility() {
const module = await import('./utils.js');
const addFunction = module.default;
console.log(addFunction(5, 3)); // 8
}
Direct Destructuring
You can also destructure the .default property directly in the import statement:
async function calculate() {
const { default: add } = await import('./utils.js');
console.log(add(10, 20)); // 30
}
Notice the : syntax—you're extracting the default property and renaming it to add in one step.
Why .default?
Think of the module namespace object like a toolbox. Named exports are tools labeled by name, but the default export sits in a special compartment labeled "default." You need to open that specific compartment to retrieve it.
This differs from static imports (import add from './utils.js'), where JavaScript automatically unwraps the default export for you.
Key Takeaway: When using dynamic imports, default exports must be accessed via the .default property on the returned module namespace object, either through dot notation or destructuring.