Skip to content

Instantly share code, notes, and snippets.

Created November 16, 2021 14:09
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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.


If your original code was:

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


then your new code must be something like this:

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



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')



Other resources

Pure ESM Package

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