Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.2 — Dynamic import() and Code Splitting
JavaScript · Example 2 of 3

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.

01

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.

02

Turn this into lazy loading: import { format } from "./big-date-lib.js"; button.onclick = () => (out.textContent = format(new Date()));.

Explain it without notes

01

How does import() differ from a static import declaration?

02

What does the promise from import() resolve to, and how do you reach the default export?

03

What is code splitting, and how does a bundler decide where to split?

04

What are the costs of lazy loading, and how do you reduce them?

The promise, the namespace object, caching and errors

Preview

Press Run to see the page.

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