Created
May 1, 2022 03:13
-
-
Save drodsou/93f19a9348cbc3c072b012205a61268d to your computer and use it in GitHub Desktop.
Import typescript from javascript esm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import esbuild from 'esbuild'; | |
import fs from 'fs'; | |
import os from 'os'; | |
import crypto from 'crypto'; | |
/** | |
* dynamic import a typescript file from javascript esm | |
*/ | |
export default async function tsImport (tsFile) { | |
tsFile = normalizePath(tsFile); | |
let tmpFile = getTempFile('mjs'); | |
console.log({tmpFile}); | |
await esbuild.build({ | |
entryPoints: [tsFile], | |
bundle: true, | |
target: 'esnext', | |
format: 'esm', | |
outfile: tmpFile, | |
}) | |
let mod = await import('file://' + tmpFile) | |
.finally(()=>{ | |
fs.promises.rm(tmpFile); | |
}) | |
return mod; | |
} | |
// -- test | |
// ;(async ()=>{ | |
// // let mod = await tsImport('uno.ts'); | |
// mod.default(); | |
// })(); | |
// -- HELPERS | |
function getTempFile (ext) { | |
return fs.realpathSync(os.tmpdir()) | |
.replace(/\\/g,'/') + '/' | |
+ crypto.randomUUID() | |
+ '.' + ext; | |
} | |
function normalizePath (filePath) { | |
let newFilePath = filePath | |
.replace(/\\/g,'/') | |
.replace(/^file:\/\//,''); | |
// Windows, /C:/somedir => C:/somedir | |
if (newFilePath.match(/^\/.:/)) { | |
newFilePath = newFilePath.slice(1) | |
} | |
return newFilePath | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment