6

Usage of ESM modules in CommonJS world.

 2 years ago
source link: https://gist.github.com/ShogunPanda/fe98fd23d77cdfb918010dbc42f4504d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK