File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed
Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change 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
5274Establishing the best way to support cjs and esm and how to structure project to enable that (see results.txt for more info)
You can’t perform that action at this time.
0 commit comments