Import ESM module in a CommonJS module

November 16, 2021 · View on GitHub

Do not use requires or top-level imports (if you're transpiling server side code). Replace all occurrences with await import and wrap your code in a async function.

Example

If your original code was:

const { someFunction= require('some-module')

someFunction('AWESOME!')

then your new code must be something like this:

async function main() {
  const { someFunction= await import('some-module')

  someFunction('AWESOME!')
}

main().catch(console.error)

Import ESM modules in a TypeScript CommonJS module

Considering what we saw in the previous paragraph, you might incur into microsoft/TypeScript#43329. In that case the workaround is to define (using a new Function) which internally performs the import:

const importDynamic = new Function("modulePath", "return import(modulePath)")

async function main() {
  const { someFunction= await importDynamic('some-module')

  someFunction('AWESOME!')
}

main().catch(console.error)

Other resources

Pure ESM Package