| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
load-esm is a tiny utility that lets CommonJS (CJS) TypeScript projects dynamically import pure ESM packages at runtime—without hacks like eval().
It helps avoid errors like:
npm install load-esm
# or
yarn add load-esm
# or
pnpm add load-esmWorks in CJS TypeScript projects. No config changes required.
// TypeScript (CJS project)
import { loadEsm } from "load-esm";
(async () => {
const esmModule = await loadEsm("esm-module");
// use esmModule...
})();import { loadEsm } from "load-esm";
(async () => {
const esmModule = await loadEsm<typeof import("esm-module")>("esm-module");
// esmModule is fully typed
})();import { loadEsm } from "load-esm";
(async () => {
try {
// Import a pure ESM package from a CommonJS TS project
const { fileTypeFromFile } = await loadEsm<typeof import("file-type")>(
"file-type"
);
const type = await fileTypeFromFile("fixture.gif");
console.log(type);
} catch (error) {
console.error("Error importing module:", error);
}
})();Note: Because top‑level await isn’t available in CommonJS, examples use an async IIFE.
function loadEsm<T = unknown>(name: string): Promise<T>Parameters
Returns
In CJS TypeScript projects ("module": "commonjs"), the TS compiler transpiles dynamic import() to require(), which breaks when the target is a pure ESM package.
load-esm executes the import() outside of TypeScript’s transpilation scope, preserving native dynamic import() semantics at runtime. This keeps your code type‑safe while avoiding brittle workarounds (e.g., wrapping import() in eval()).
Since Node.js 22.12, require can load some ESM modules, but there are documented constraints. If your dependencies are compatible with that path, you might not need this utility. load-esm remains useful when:
If Node’s built‑in require(esm) works for your packages and version, feel free to use it.
See Releases.
Inspired by common pain points when mixing CJS projects with modern ESM‑only libraries.
| Back | FazBrowse Home | New Git URL |