Dynamic Import in CommonJS
You'll learn how to use import() expressions inside CommonJS files to load ES Modules asynchronously.
The Bridge Between Two Worlds
Remember when we covered "Requiring ESM from CJS" and hit a wall? You can't use require() to load ES Modules in CommonJS—it's synchronous and incompatible. But there's a solution: the dynamic import() function works everywhere, including inside CommonJS files.
How Dynamic Import Works in CommonJS
Even though you're writing a CommonJS module (using module.exports and require()), you can still call import() to load an ES Module asynchronously:
// my-cjs-file.js (CommonJS)
async function loadESModule() {
const esmModule = await import('./my-esm-file.mjs');
console.log(esmModule.default); // Access default export
console.log(esmModule.namedExport); // Access named exports
}
loadESModule();
The import() function returns a promise that resolves to the module object, so you typically use it with async/await or .then().
Why This Matters
This is your migration path. If you have an older CommonJS codebase but want to start using modern ES Modules (or npm packages that have switched to ESM-only), dynamic import lets you do it gradually without rewriting everything at once.
// legacy.cjs
module.exports = async function processData(input) {
// Load a new ESM-only package
const { transform } = await import('esm-only-package');
return transform(input);
};
Key Takeaway: Use import() expressions (dynamic imports) inside CommonJS files to asynchronously load ES Modules—it's the only way to bridge from CJS to ESM without converting your entire file.