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.
Code
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 importInside 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:pathresolves 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does this require external packages?
- No — `node:path` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.