You can import ESM modules (including pure ESM modules, like `p-limit), in CommonJS.
The reason this does not work in a TypeScript module, is because the TypeScript compiler converts the import()
to a require()
. The asynchronous import(), also called dynamic import, is requried to load an ESM module.
The following code will load an ESM module in a CommonJS project:
The load-esm
library performs the import operation outside the scope of the TypeScript compiler, avoiding the import
being transpiled to require()
.
There are several methods to workaround this problem.
import {loadEsm} from 'load-esm';
(async () => {
const esmModule = await loadEsm('esm-module');
})();
To incude the types of the project, you need to make the following changes:
import {loadEsm} from 'load-esm';
(async () => {
const esmModule = await loadEsm<typeof import('esm-module')>('esm-module');
})();
This answer is based on:
load-esm
.An alternative approach is wrapping the import()
in an eval()
, yet that has some disadventages, see: Why is using the JavaScript eval function a bad idea?