Last active
September 23, 2021 11:57
-
-
Save amatiasq/04466a506dd5a91b28b439514613748c to your computer and use it in GitHub Desktop.
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
const extensions = { | |
js: 'application/javascript', | |
ts: 'application/typescript', | |
jsx: 'text/jsx', | |
tsx: 'text/tsx', | |
} as const; | |
type Extensions = typeof extensions; | |
type ValidExtension = keyof Extensions; | |
type ValidMediaType = Extensions[ValidExtension]; | |
export default function esm(lang: ValidMediaType) { | |
return (text: TemplateStringsArray, ...rest: string[]) => { | |
const code = String.raw(text, rest); | |
const metadata = `data:${lang};charset=utf-8`; | |
const uri = `${metadata},${encodeURIComponent(code)}`; | |
return import(uri); | |
}; | |
} | |
export const js = esm(extensions.js); | |
export const ts = esm(extensions.ts); | |
export const jsx = esm(extensions.jsx); | |
export const tsx = esm(extensions.tsx); | |
export function isValidExtension(ext: string): ext is ValidExtension { | |
return ext in extensions; | |
} |
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 ts from "./esm.ts" | |
const module = await ts`export const a = "hi!"`; | |
console.log(module.a) // hi! |
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 * as esm from "./esm.ts" | |
const path = 'path/to/myfile.ts' | |
const ext = getExtensionFrom(path) | |
if (!esm.isValidExtension(ext)) { | |
throw new Error(`Invalid extension ${ext}`) | |
} | |
const content = await Deno.readTextFile(path) | |
const module = esm[ext]`${content}`; | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment