load-esm is a lightweight utility designed for TypeScript projects configured with CommonJS (`"module": "commonjs"`) that need to dynamically load pure ECMAScript Modules (ESM) at runtime. It directly addresses common interoperability errors such as `Error [ERR_REQUIRE_ESM]: require() of ES Module` and `Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in ...`. The utility functions by executing the native `import()` call outside of TypeScript's CommonJS transpilation scope, thereby preserving the correct dynamic import semantics at runtime. This approach provides a robust and type-safe solution without resorting to brittle workarounds like `eval()`. The current stable version is 1.0.3, with releases primarily focused on documentation improvements and ensuring compatibility with evolving Node.js and TypeScript ecosystems. Its key differentiator is providing a consistent, reliable mechanism for ESM-in-CJS loading across various Node.js versions, even beyond Node.js 22.12's `require()`-based ESM loading limitations.
npm install load-esmVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to dynamically import a pure ESM package (e.g., 'file-type') within a CommonJS TypeScript project, utilizing `loadEsm` with proper TypeScript generic typings for full inference.
Rename all calls to `loadModule(...)` to `loadEsm(...)`.
Wrap `loadEsm` calls within an `(async () => { ... })();` block or inside a named `async function`.Evaluate if Node.js's built-in `require(esm)` fully meets your needs, otherwise, `load-esm` offers a more robust solution for dynamic imports.
Update `loadEsm('pkg')` calls to `loadEsm<typeof import('pkg')>('pkg')` to leverage full type safety.Use `loadEsm('esm-module')` instead of `import('esm-module')` or `require('esm-module')` when in a CommonJS TypeScript project targeting pure ESM packages.Import the package using `await loadEsm('package-name')` to correctly resolve its ESM entry points.Provide a type argument to `loadEsm`: `await loadEsm<typeof import('my-esm-package')>('my-esm-package')`.No dependency data recorded yet.