Dynamic import and CJS interop
import() is an expression that loads an ES module asynchronously and returns a promise for its module namespace. Node also allows ES modules to import CommonJS modules. A CommonJS module’s exported value is available as the default import from ESM.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Load a local ES module with import()
const namespace = await import("./formatter.mjs");console.log(namespace.format(8));In the directory containing the files above, run:
node main.mjsExpected standard output:
Item 8Expected exit status: 0.
How it works
Use static imports when the dependency is always required. Dynamic import is useful for conditionally loading a reviewed module or for importing ESM from CommonJS. The promise resolves to a namespace whose properties correspond to exported names. In the first fixture a local formatter is selected from a fixed, trusted specifier. The second fixture imports the module.exports object from CommonJS as a default value. Node may also detect some CommonJS named exports, but this depends on static analysis and is not a general guarantee. Modern Node releases can synchronously require certain ESM graphs that contain no top-level await; this is version-specific and not required for these fixtures.
Import a CommonJS export from ESM
In the directory containing the files above, run:
node main.mjsExpected standard output:
Legacy catalogExpected exit status: 0.
Common mistake
import() returns a promise, not the exported value immediately. Await it or handle its fulfillment and rejection. Never accept arbitrary module paths or remote code URLs from user input. Do not assume detected named exports from CommonJS behave like native ESM live bindings.
Try it yourself
Create a second reviewed local formatter. Select between two fixed import expressions based on a hardcoded mode string, await the result and print one formatted ID. Then change the mode. Do not build an import path directly from external input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dynamic import and CJS interop — knowledge check
Check your understanding of dynamic import and cjs interop.
What does import() return?
How does the ESM fixture obtain the legacy object?
Which dependency loading choice is safest for the shown example?