Skip to content

Instantly share code, notes, and snippets.

@ShogunPanda
Created November 16, 2021 14:09
Show Gist options
  • Save ShogunPanda/fe98fd23d77cdfb918010dbc42f4504d to your computer and use it in GitHub Desktop.
Save ShogunPanda/fe98fd23d77cdfb918010dbc42f4504d to your computer and use it in GitHub Desktop.
Usage of ESM modules in CommonJS world.

Import ESM module in a CommonJS module

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment