Dynamic import() Loads Modules Lazily

Load a module on demand with dynamic import(), read its typed exports, and keep the import inside an async function so startup stays lazy.

TypescriptConfig Management

Code

typescriptsnippet
20 lines
async function loadPathHelpers() {
  const path = await import("node:path");

  const joined = path.join("content", "examples", "python");
  console.log("joined:", joined);
  console.log("basename:", path.basename(joined));
  console.log("separator:", path.sep);
  console.log("is absolute:", path.isAbsolute(joined));

  return path;
}

async function main() {
  console.log("before import");
  const pathModule = await loadPathHelpers();
  console.log("join type:", typeof pathModule.join);
  console.log("after import");
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

before import
joined: content\examples\python
basename: python
separator: \
is absolute: false
join type: function
after import

Inside the snippet

Dynamic import() Loads Modules Lazily reduces to the functions loadPathHelpers and main.

Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Watch out for

  • node:path resolves inside Node.js without any package — it is a core module.

Using it

The entry-point signature is async function loadPathHelpers()

The run emits 7 labeled sections — joined:, basename:, separator:, is absolute:, before import, join type:, after import — one per step.

main sequences loadPathHelpers; executing the file runs that flow once.

Key statements

const pathModule = await loadPathHelpers();
const path = await import("node:path");

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:path` is a Node.js built-in module; nothing to install.