Skip to content

Commit 441b9f7

Browse files
authored
add dynamic import load module example
1 parent a22c5c1 commit 441b9f7

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,28 @@
4747
//...
4848
```
4949
50+
## `load-esm.{ts,mts}`
51+
52+
```typescript
53+
import { URL } from 'url';
54+
55+
/**
56+
* This uses a dynamic import to load a module which may be ESM.
57+
* CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript
58+
* will currently, unconditionally downlevel dynamic import into a require call.
59+
* require calls cannot load ESM code and will result in a runtime error. To workaround
60+
* this, a Function constructor is used to prevent TypeScript from changing the dynamic import.
61+
* Once TypeScript provides support for keeping the dynamic import this workaround can
62+
* be dropped.
63+
*
64+
* @param modulePath The path of the module to load.
65+
* @returns A Promise that resolves to the dynamically imported module.
66+
*/
67+
export function loadEsmModule<T>(modulePath: string | URL): Promise<T> {
68+
return new Function('modulePath', `return import(modulePath);`)(modulePath) as Promise<T>;
69+
}
70+
```
71+
5072
## Motivation
5173
5274
Establishing the best way to support cjs and esm and how to structure project to enable that (see results.txt for more info)

0 commit comments

Comments
 (0)