The promise, the namespace object, caching and errors
The default export lives on the property default; destructuring renames it with default: greet. The second import didn't run the module again. A module that throws makes the promise reject, so catch sees the error.
import(specifier) loads a module while the program is running and returns a promise of its namespace object, so code can be fetched only when it is needed; bundlers use it to split an app into smaller files called chunks.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write an async function loadAndRun(url) that imports a module, calls its default export with no arguments, and returns the result; if anything fails it returns the string failed.
Turn this into lazy loading: import { format } from "./big-date-lib.js"; button.onclick = () => (out.textContent = format(new Date()));.
Explain it without notes
How does import() differ from a static import declaration?
What does the promise from import() resolve to, and how do you reach the default export?
What is code splitting, and how does a bundler decide where to split?
What are the costs of lazy loading, and how do you reduce them?
Preview
Console
Nothing logged yet.Expected console output
import() returned a Promise
greeting module runs
Hi Asha version 2
second import: same function? true version 2
Caught: the module crashed while running