Skip to content

Instantly share code, notes, and snippets.

Last active September 23, 2021 11:57
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save amatiasq/04466a506dd5a91b28b439514613748c to your computer and use it in GitHub Desktop.
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, 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;
import ts from "./esm.ts"
const module = await ts`export const a = "hi!"`;
console.log(module.a) // hi!
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