-
Notifications
You must be signed in to change notification settings - Fork 7
/
mod.ts
36 lines (29 loc) · 1.01 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import * as esbuild from 'https://deno.land/x/esbuild@v0.14.53/wasm.js'
import { denoPlugin } from 'https://deno.land/x/esbuild_deno_loader@0.5.2/mod.ts'
const AsyncFunction = (async function () {}).constructor
export async function importModule(
moduleName: string
): Promise<Record<'default' | string, any>> {
try {
return await import(moduleName)
} catch {
esbuild.initialize({ worker: false })
const result = await esbuild.build({
bundle: true,
plugins: [ denoPlugin() ],
write: false,
logLevel: 'silent',
format: 'esm',
entryPoints: [ import.meta.resolve(moduleName) ],
})
esbuild.stop()
const { text } = result.outputFiles[ 0 ]
const [ before, after ] = text.split('export {')
const body =
before
+ (after
? 'return {' + after.replaceAll(/(\w+) (as) (\w+)/gi, '$3: $1')
: '')
return AsyncFunction(body)()
}
}