Import ESM libraries into commonjs project Error [ERR_REQUIRE_ESM]: require() of ES Module -

66 Views Asked by At

Problem

I have a 'commonjs' typescript project and I need to add several npm dependencies that are ESM packages.

I can't move my project from type: 'commonjs' to type: 'module at the moment and I am unable to downgrade the version of the libraries I require.

When I attempt to build/run my application after importing ESM libraries, I get the following error

Error [ERR_REQUIRE_ESM]: require() of ES Module <path to ESM library index.js> not supported.
Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.

Question

Is it possible to import an ESM package into a commonjs project?

Attempts

I have tried a few solutions from the following posts but nothing seems to work. I always get the same error.

Sample code

Github repo

Run npm i && npm run dev

1

There are 1 best solutions below

8
Evert On

Is it possible to import an ESM package into a commonjs project?

Yes, use dynamic import:

const somePackage = await import('package-name');