79319627

Date: 2024-12-31 09:36:23
Score: 1.5
Natty:
Report link

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:

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?

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Mid March