load-esm

1.0.3 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { loadEsm } from "load-esm";

(async () => {
  try {
    // This example demonstrates loading the 'file-type' package, a pure ESM module.
    // To run this, install 'file-type' (npm install file-type) and ensure
    // 'fixture.gif' (or any valid file) exists in your project root.

    // The generic type argument `typeof import("file-type")` provides full type inference.
    const { fileTypeFromFile } = await loadEsm<typeof import("file-type")>(
      "file-type"
    );

    const type = await fileTypeFromFile("fixture.gif");
    console.log("Detected file type:", type); // e.g., { ext: 'gif', mime: 'image/gif' }
  } catch (error) {
    console.error("Error importing module or processing file:", error);
    // Common errors caught here include ERR_REQUIRE_ESM and ERR_PACKAGE_PATH_NOT_EXPORTED.
  }
})();

view raw JSON →