ProgramGuru

Dynamic Imports

Dynamic Imports — the core idea

Dynamic import() loads a module on demand and returns a Promise for its module namespace. It can defer optional functionality, but errors must be handled if a module cannot be resolved. Static imports, in contrast, are declared at module top level.

What you’ll learn

  • Explain dynamic imports with a concrete use case.
  • Run the example and account for every line of its output.
  • Recognize the difference between compile-time checking and runtime behavior.

Understand the rules and when to use them

Reading the code: In the CommonJS teaching build, import("./main") resolves the compiled module itself; the Promise provides its exports and formatter produces #8. In a real project, import a separate optional module to avoid self-import.

Keep the boundary clear: Never assume that dynamic import is always code-split; the bundler and build configuration determine how the module is packaged.

See the idea as a flow

Dynamic Imports — conceptual flowawait import(...) then Promise → module namespace then use formatterDynamic Imports1await import(...)2Promise → module namespace3use formatterMatch the compiler configuration to the JavaScript environment.
Follow the three stages and identify what happens in TypeScript versus JavaScript.

Run the complete TypeScript example

Save the code as dynamic-imports.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.

TypeScript code

export const formatter = (value: number): string => `#${value}`;
async function main(): Promise<void> {
  const module = await import("./dynamic-imports");
  console.log(module.formatter(8));
}
main().catch(console.error);

Verified output

#8

Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable dynamic-imports.ts; run: node dynamic-imports.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.

Trace the example line by line

In the CommonJS teaching build, import("./main") resolves the compiled module itself; the Promise provides its exports and formatter produces #8. In a real project, import a separate optional module to avoid self-import.

The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.

Build the real multi-file example

This separate mini-project demonstrates real imports, exports, or declarations across files. Create each file in one folder, then compile and run main.js. The example was checked separately from the single-file program.

formatter.ts

export function label(n:number){return `#${n}`;}

main.ts

async function run(){const mod=await import("./formatter");console.log(mod.label(7));}run().catch(console.error);

CommonJS setup: compile with npx tsc --strict --target es2022 --module commonjs main.ts and run node main.js. Compile from the same directory so relative modules are discovered. If this example contains helpers.js, keep that runtime file alongside the emitted main.js.

Verified output from the mini-project

#7

Avoid this common mistake

Never assume that dynamic import is always code-split; the bundler and build configuration determine how the module is packaged.

Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.

Practice independently

Move formatter into formatter.ts, dynamically import that file, and handle import rejection.

Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.

Check your understanding

Does dynamic import() return a module namespace immediately?
Choose one answer. You can try again.

Answer and explanation

No. import() returns a Promise for the module namespace.

In the CommonJS teaching build, import("./main") resolves the compiled module itself; the Promise provides its exports and formatter produces #8. In a real project, import a separate optional module to avoid self-import.

What to remember

Dynamic import() loads a module on demand and returns a Promise for its module namespace.

Try the practice change and re-run the exact program to test your understanding.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Organizing Code Across Files →